基于Python实现船舶的MMSI的获取(推荐)

  import requests

  import os

  import time

  import pymysql

  import pandas as pd

  import re

  '''

  author:shikailiang

  function:通过读取船舶数据,分别请求拿到json数据入库

  '''

  #定义入库的类

  class company_ship_in_database:

  def __init__(self):

  self.conn = pymysql.connect(host="192.168.1.222", user="root", password="Cjh#Sjzx@", database="test", charset="utf8")

  self.cursor = self.conn.cursor()

  #获取当前文件的父级地址

  self.last_path = os.path.abspath(os.path.dirname(os.getcwd()))

  #写入mysql

  def in_database(self,data_list):

  #j用来对数据进行计数

  j=1

  #定义sql

  sql = ""

  #定义sql头

  sql0 = "insert into bms_company_ship_test(oc_name,ship_name,mmsi) values"

  rowcount=len(data_list)

  for i in data_list:

  #定义拼接sql

  sql2 = (("(" + "'{}'," * 3)[:-1] + ")").format(i[1][0],i[1][1],i[0])

  sql = sql + "," + sql2

  # print(sql0 + sql[1:])

  if divmod(j, 300)[1] == 0 or j == rowcount:

  #如果执行错误回滚当前事务

  # print(sql0 + sql[1:])

  try:

  self.cursor.execute(sql0 + sql[1:])

  except:

  #执行错误,回滚事务

  self.conn.rollback()

  continue

  sql= ""

  self.conn.commit()

  j=j+1

  #通过pandas写入excel

  def in_xls(self, data_list):

  df=pd.DataFrame(data_list)

  #通过pandas实现存为excel

  df.to_excel(self.last_path + r"data

  esult.xls",header=False,index=False)

  #请求船的方法

  def company_ship_in_database(self):

  data_path = self.last_path + r"data"

  file=open(data_path + "company.txt")

  data=[]

  j = 0

  for i in file.readlines():

  #将船公司和船舶名称分开

  chuan=i.strip().split()

  dic={

  'f':'auto',

  'kw':chuan[1]

  }

  rq=requests.get("http://searchv3.shipxy.com/shipdata/search3.ashx",params=dic)

  #判断是否请求成功

  if rq.status_code==200:

  try:

  result_json=rq.json()

  result=result_json['ship'][0]

  #判断船舶数字部分是否相同

  if re.search('d+',result['n']).group()==re.search('d+',chuan[1]).group():

  result=result['m']

  data.append([result,chuan])

  else:

  data.append(["", chuan])

  except:

  data.append(["",chuan])

  else:

  print(chuan + "请求错误")

  time.sleep(0.5)

  j = j + 1

  if divmod(j,100)[1] == 0:

  print("已经请求" + str(j) + "条")

  # if j > 10:

  # self.in_xls(data)

  # break

  self.in_database(data)

  if __name__=="__main__":

  company_ship=company_ship_in_database()

  company_ship.company_ship_in_database()