# -*- coding = ut-8 -*-
# @Time : 2021/4/25 10:42
# @Author : PHC
# @File test_mysql.py
# @Software : PyCharm
import sys
import io
import datetime
import time
import os
import pandas as pd
import json
import requests
import jsonpath
import openpyxl
import wx
import wx.grid
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
wildcard1 = "All files (*.*)|*.*|" \
"Python source (*.py; *.pyc)|*.py;*.pyc"
wildcard2 = "Python source (*.py; *.pyc)|*.py;*.pyc|" \
"All files (*.*)|*.*"
curr_time = datetime.datetime.now()
time_str = curr_time.strftime("%Y%m%d") # 2019-07-06
#文件生成位置
Findship_list_filename=r"D:\pyharm\TestTrue\嘟嘟找船ship_list"+time_str+".xlsx"
Bossship_list_filename=r"D:\pyharm\TestTrue\船老板ship_list"+time_str+".xlsx"
time1=time.localtime()
print("这个时间是",time1)
exception_url = [] # 异常url存储列表
# class MyForm(wx.Frame):
#
# # -------------------------------------------------------------------
# # set the window layout
# def __init__(self):
# wx.Frame.__init__(self, None, wx.ID_ANY, \
# "Multi-file type wx.FileDialog Tutorial", \
# pos=(0, 0), size=(1200, 735))
# # def the global variance
# global TxtCfn, grid,TxtC_mmsi,TxtC_output,TxtC_location
# # layout the Frame
# panel = wx.Panel(self, wx.ID_ANY)
# TxtCfn = wx.TextCtrl(panel, pos=(15, 5), size=(200, 25))
# btnO = wx.Button(panel, label="选择货源文件", pos=(215, 5), size=(100, 25))
# btnS = wx.Button(panel, label="上传到数据库", pos=(315,5), size=(100, 25))
# btn_loadout = wx.Button(panel, label="导出ship位置信息", pos=(115, 35), size=(120, 25))
# btn_updateship = wx.Button(panel, label="更新船位置信息", pos=(15, 35), size=(100, 25))
# wx.StaticText(panel, -1, "MMSI:",(15, 65))
# TxtC_mmsi = wx.TextCtrl(panel, pos=(60, 65), size=(100, 25))
# btn_shipinfo = wx.Button(panel, label="船基础信息", pos=(160, 65), size=(100, 25))
# btn_exportplace = wx.Button(panel, label="导出停靠位置", pos=(260, 65), size=(100, 25))
# btn_shuilulianyun_track= wx.Button(panel, label="历史停靠", pos=(360, 65), size=(100, 25))
# btn_delpyshipinfo = wx.Button(panel, label="爬虫去重", pos=(460, 65), size=(100, 25))
#
# wx.StaticText(panel, -1, "输入位置:", (15, 95))
# btn_getnearship = wx.Button(panel, label="获取周边船只", pos=(290, 90), size=(100, 25))
# btn_test= wx.Button(panel, label="嘟嘟找船", pos=(390, 90), size=(100, 25))
# # btn_chuanlaoda = wx.Button(panel, label="船老大", pos=(690, 90), size=(100, 25))
# # btn_shuilulianyun = wx.Button(panel, label="水陆联运", pos=(790, 90), size=(100, 25))
# btn_xinchuanbang = wx.Button(panel, label="新船帮", pos=(490, 90), size=(100, 25))
# btn_chuanlaoban = wx.Button(panel, label="船老板", pos=(590, 90), size=(100, 25))
# # btn_chuanhuotong= wx.Button(panel, label="船货通", pos=(890, 90), size=(100, 25))
#
#
# TxtC_location = wx.TextCtrl(panel, pos=(80, 90), size=(200, 25), style=wx.TE_MULTILINE | wx.TE_RICH2)
# TxtC_output = wx.TextCtrl(panel, pos=(15, 120), size=(600, 200), style=wx.TE_MULTILINE | wx.TE_RICH2)
# grid = wx.grid.Grid(panel, pos=(15, 320), size=(1200, 600),
# style=wx.TE_MULTILINE | wx.HSCROLL)
# grid.CreateGrid(100, 10)
# grid.SetRowSize(0, 60)
# columns = ['id', 'mmsi', 'shipname', 'tone', 'contract', 'phone', 'person_type', 'lo', 'la', 'address', 'time'];
# for index, col_name in enumerate(columns):
# grid.SetColLabelValue(index, col_name);
# # Contents = wx.TextCtrl(panel, pos=(15, 35), size=(360, 260),
# # style=wx.TE_MULTILINE | wx.HSCROLL)
# # bind the button event
# btnO.Bind(wx.EVT_BUTTON, self.onOpenFile)
# btnS.Bind(wx.EVT_BUTTON, self.onSaveFile)
# btn_loadout.Bind(wx.EVT_BUTTON, self.loadoutUserInfo)
# btn_updateship.Bind(wx.EVT_BUTTON, self.updateshipinfo)
# btn_shipinfo.Bind(wx.EVT_BUTTON, self.gethifleetshipinfo)
# btn_exportplace.Bind(wx.EVT_BUTTON, self.exportvorge)
# btn_delpyshipinfo.Bind(wx.EVT_BUTTON, self.delpythonshipinfo)
# btn_getnearship.Bind(wx.EVT_BUTTON, self.getnearship)
# btn_test.Bind(wx.EVT_BUTTON, self.duduzhaochuan)
# # btn_chuanlaoda.Bind(wx.EVT_BUTTON, self.chuanlaoda)
# # btn_shuilulianyun.Bind(wx.EVT_BUTTON, self.shuilulianyun)
# btn_shuilulianyun_track.Bind(wx.EVT_BUTTON, self.getshuilulianyunTrack)
# btn_xinchuanbang.Bind(wx.EVT_BUTTON, self.xinchuanbang)
# btn_chuanlaoban.Bind(wx.EVT_BUTTON, self.chuanlaoban)
# # btn_chuanhuotong.Bind(wx.EVT_BUTTON, self.chuanhuotong_fillinfo)
class MyForm(wx.Frame):
#图形化界面,组件控制器
def __init__(self):
#各参数意思
wx.Frame.__init__(self,None,wx.ID_ANY,\
"Multi-file type wx.FileDialog Tutor",\
pos=(0,0) ,size=(1200,735))
#定义全局方差
global TxtCfn,grid,TxtC_mmsi,TxtC_output,TxtC_location
#布局框架
panel=wx.Panel(self,wx.ID_ANY)
# TxtCfn=wx.Button(panel,pos=(15,5),size=(200,25))
# btn0=wx.Button(panel,label="上传货源文件",pos=(215,5),size=(100,25))
# btnS=wx.Button(panel,label="上传到数据库",pos=(315,5),size=(100,25))
# btn_loadout=wx.Button(panel,label="导出ship位置信息",pos=(115,35),size=(100,25))
# btn_updateship=wx.Button(panel,label="更新船位置信息",pos=(15,35),size=(199,25))
# wx.StaticText(panel,-1,"MMSI:",(15,65))
# TxtC_mmsi=wx.TextCtrl(panel,pos=(60,65),size=(100,25))
# btn_shipinfo=wx.Button(panel,label="船基础信息",pos=(160,65),size=(100,25))
# btn_exportplace=wx.Button(panel,label="导出停靠位置",pos=(260,65),size=(100,25))
btn_test = wx.Button(panel, label="嘟嘟找船", pos=(390, 90), size=(100, 25))
btn_chuanlaoban=wx.Button(panel,label="船老板",pos=(590,90),size=(100,25))
#wx.TextCtrl 会创建一个文本编辑框
# TxtC_location=wx.TextCtrl(panel,pos=(80,90),size=(200,25),style=wx.TE_MULTILINE | wx.TE_RICH2)
TxtC_output = wx.TextCtrl(panel, pos=(15, 120), size=(600, 200), style=wx.TE_MULTILINE | wx.TE_RICH2)
grid=wx.grid.Grid(panel,pos=(15,320),size=(1200,600),
style=wx.TE_MULTILINE | wx.HSCROLL)
grid.CreateGrid(100,10)
grid.SetRowSize(0,60)
columns=['id','mmsi','shipname','tone','contract','phone','person_type','lo','la','address','time'];
for index,col_name in enumerate(columns):
grid.SetColLabelValue(index,col_name);
#绑定按钮事件
# btn0.Bind(wx.EVT_BUTTON,self.onOpenFile) #选择货源
#btnS.Bind(wx.EVT_BUTTON,self.onSaveFile) #上传到数据库
# btn_loadout.Bind(wx.EVT_BUTTON,self.loadoutUserInfo) #导出ship的位置
btn_test.Bind(wx.EVT_BUTTON,self.duduzhaochuan) #嘟嘟找船
btn_chuanlaoban.Bind(wx.EVT_BUTTON,self.chuanlaoban) #船老板
# 辅助接口
def is_valid_date(self,strdate):
#判断是否是一个有效的日期字符串
try:
if ":" in strdate:
time.strptime(strdate,"%Y-%m-%d %H:%M:%S") #根据指定的格式把一个时间字符串解析为时间元组
else:
tiem.strptime(strdate,"%Y-%m-%d")
return True
except:
return False
#嘟嘟找船
def duduzhaochuan(self,event):
if True==os.path.exists(Findship_list_filename):
#将Excel文件读取到pandas DataFrame中,支持本地文件系统或URL的’xls’和’xlsx’文件扩展名,
data_df=pd.read_excel(Findship_list_filename)
else:
data_df=pd.DataFrame(
columns=['联系人','电话','船名','吨位','始发地','到达地','起运日','截运日','备注','来源']);
data=json.dumps({ #编码:把一个Python对象编码转换成Json字符串 json.dumps()
"method": "get_recommended_shipping_with_cargo",
"params": {"cargo_id": "", "max": "100", "page": "1", "start_max": "50", "n_port": "",
"weight": "",
"has_cover": "", "has_crane": "", "has_monitor": "", "order": "",
"access_token": "npguIXimR6mB5VUrtx2iHA==i/xybASc2VaCsDEKxrcVbA==8ea734660924fddcf8b6350b40b32f82",
"query_word": ""}, "id": "1586154325480"})
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'Dalvik/2.1.0(Linux;U;Android 9; ALP-AL00 Build / HUAWEIALP - AL00)'
}
response = requests.post("https://api.haoyunhl.com/index.php/Cargo", data=data, headers=header)
#打印客户端接收到的HTTP响应的文本内容
print(response.text)
print("========================================================================================================================")
data_list=[]
if response.status_code==200:
# ==== 解码:把Json格式字符串解码转换成Python对象 json.loads()
jsonstr=json.loads(response.text)
print(jsonstr)
contract=jsonpath.jsonpath(jsonstr,'$..username')
phone_list=jsonpath.jsonpath(jsonstr,'$..mobile')
shipname=jsonpath.jsonpath(jsonstr,'$..name')
cdate = jsonpath.jsonpath(jsonstr, '$..u_time')
# lng = jsonpath.jsonpath(jsonstr, '$..lng')
# lat = jsonpath.jsonpath(jsonstr, '$..lat')
start = jsonpath.jsonpath(jsonstr, '$..n_port')
remark = jsonpath.jsonpath(jsonstr, '$..remark')
# arrive = jsonpath.jsonpath(jsonstr, '$..destination_address')
tone = jsonpath.jsonpath(jsonstr, '$..deadweight')
for index,phone in enumerate(phone_list):
now=time.time() #返回当前时间的时间戳(1970纪元后经过的浮点秒数)。
if((now-int(cdate[index]))<=86400) or (phone==None):
if(self.is_valid_date(cdate[index])==False):
dateArray=datetime.datetime.fromtimestamp(int(cdate[index]))
otherStyleTime=dateArray.strftime("%Y/%m/%d")
cdate[index]=otherStyleTime;
timeArray1=time.localtime(now+259200);
otherStyleTime1=time.strftime("%Y/%m/%d",timeArray1)
data_df=data_df.append(
pd.DataFrame(
{'联系人': [contract[index]], '电话': [phone], '船名': [shipname[2 * index]], '吨位': [tone[index]],
'始发地': [start[index]], '备注': [remark[index]], '到达地': [" "],
'起运日': [cdate[index]], '截运日': [otherStyleTime1], '来源': ["嘟嘟找船"]},
index=[data_df.shape[0]]), ignore_index=True);
writer=pd.ExcelWriter(Findship_list_filename)
data_df.to_excel(writer,engine='xlswriter',float_format='%.5f',index=False)
writer.save()
#查看响应内容,response.content返回的字节流数据
print("****************************************************************************************************")
print(response.content)
#查看完整的url地址
print(response.url)
#查看响应头部字符编码
print(response.encoding)
#-----船老板-----船老板-----船老板-----船老板-----船老板-----船老板-----船老板-----船老板-----船老板-----船老板-----船老板
def chuanlaoban(self,event):
if True==os.path.exists(Bossship_list_filename):
data_df=pd.read_excel(Bossship_list_filename)
else:
# pd.DataFrame是Pandas库中的一种数据结构,类似Excel,是一种二维表
#DataFrame可以设置列名,columns,与行名index。 columns是DataFrame中的属性。设置列。
data_df=pd.DataFrame( columns=['联系人', '电话', '船名', '吨位', '始发地', '到达地', '起运日', '截运日', '备注', '来源']);
#-------------------json.dumps---编码,把一个Python对象编码转换成Json字符串
data = json.dumps({"method": "get_recommended_shipping_with_cargo",
"params": {"cargo_id": "", "max": "100", "page": "1", "start_max": "50", "n_port": "",
"weight": "",
"has_cover": "", "has_crane": "", "has_monitor": "", "order": "",
"access_token": "npguIXimR6mB5VUrtx2iHA==i/xybASc2VaCsDEKxrcVbA==8ea734660924fddcf8b6350b40b32f82",
"query_word": ""}, "id": "1586154325480"})
print(type(data),"====data") #str
header = {
# 'Accept': 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'Dalvik/2.1.0(Linux;U;Android 9; ALP-AL00 Build / HUAWEIALP - AL00)'
}
requests.packages.urllib3.disable_warnings()
response = requests.get("https://api.chuan666.com/ship/lists?page=1&pagesize=100&keywords=&tj=0&fromtype=2&token=32_pRHum7q6xdqc1sWU-90NuvB5Pw4cTR-v3MODi5fQQFMzv6SZSx38AJquhu4w48GfVKj_r7w0p9WoaTiu5j-oJqRuI4hb5cW1AQlldY8kE8YtSWgGq6E7iM04GNIpKq1Ck0BTANl_3WLhegI6AOBjAHANBO ", headers=header,verify=False)
# print(response.text)
data_list = [] # 定义一个空元组。
if response.status_code==200:
# ==== 解码:把Json格式字符串解码转换成Python对象 json.loads()
jsonstr=json.loads(response.text)
print(type(jsonstr),"====jsonstr") #dict
# print("======================================================================")
# print(jsonstr)
# JSONPath-用于JSON的XPath,用来解析多层嵌套的json数据,jsonPath是一种信息抽取类库,是从文档中抽取指定信息的工具。
shipname_list = jsonpath.jsonpath(jsonstr, '$..title') # 查找jsonstr中所有的title ------> 船名
phone = jsonpath.jsonpath(jsonstr, '$..phone') # 电话
cdate = jsonpath.jsonpath(jsonstr, '$..cdate') #起运日,开始日期
lng = jsonpath.jsonpath(jsonstr, '$..lng') #
lat = jsonpath.jsonpath(jsonstr, '$..lat') # lng,lat 在后续中并未引用。
renmark = jsonpath.jsonpath(jsonstr, '$..intro') # 备注
start = jsonpath.jsonpath(jsonstr, '$..empty_address') # 始发地
arrive = jsonpath.jsonpath(jsonstr, '$..destination_address') # 到达地
tone = jsonpath.jsonpath(jsonstr, '$..dw') # 吨位
# 1、将cdate格式的字符串解析为时间元组,-------2、使用time.strftime()接收时间元组,并返回可读字符串表示的当地时间,
#enumerate()用于将一个可遍历的数据对象(如列表,元组,或者字符串) 组合为一个索引序列,同时列出数据和数据下标,一般用在for循环中
for index,shipname in enumerate(shipname_list):
#%Y-%m-%d 年-月-日
timeArray =time.strptime(cdate[2*index],"%Y-%m-%d") # cdate[2*index] 表示查找的是第二个cdate 函数根据指定的格式把一个时间字符串解析为时间元组。
# 输出结果: time.struct_time(tm_year=2021, tm_mon=5, tm_mday=6, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=126, tm_isdst=-1)
# 126 表示2021-5-6日。在2021年中已过126 天。
# print("timeArray====",timeArray)
# time.strftime() 用以接收时间元组,返回值:可读字符串表示的当地时间。 格式由format决定(即:%Y/%m/%d)
otherStyleTime = time.strftime("%Y/%m/%d", timeArray) # 起运日
# print("otherStyleTime====", otherStyleTime) # 输出结果 2021/05/06
timeStamp=int(time.mktime(timeArray)); # 返回结果是浮点值。 将时间转换为浮点秒数来表示。并转换为整型。
# print("timeStamp====",timeStamp) #输出结果:1620230400
# timeStamp = int(time.mktime(timeArray)) # 返回用秒数来表示时间的浮点数-----> 将本地时间列表转化为浮点数的秒来表示
# print("timeStamp====", timeStamp) # 输出结果 1620230400
#time.localtime() 作用是格式化时间戳为本地的时间。 输出结果是元组的形式。
timeArray1=time.localtime(timeStamp+259200); #加上3天的时间 259200====3天*(一天86400秒)。
# #输出结果: time.struct_time(tm_year=2021, tm_mon=5, tm_mday=9, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=129, tm_isdst=0)
# print("timeArray1====",timeArray1)
# time.strftime()用以接收时间元组。 返回值:可读字符串表示的当地时间。 格式由format决定(即:%Y/%m/%d)
otherStyleTime1=time.strftime("%Y/%m/%d",timeArray1) # 截运日
# print("otherStyleTime1====",otherStyleTime1) #输出结果 2021/05/06+3----> 2021/05/09
# print(index) # 输出结果---> 0-97。
# print(cdate) # 遍历jsonstr中所有的cdate的时间
# print("¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥")
# print(cdate[2*index]) #输出结果 2021-05-06 起运日时间。
now=time.time() # 返回当前时间的时间戳(1970纪元后经过的浮点秒数)。
# timeStamp=1620230400
if((now-timeStamp)<=86400) or (phone ==None): # 表示当天启航或者电话为空
tup = ("匿名", phone[index],shipname, tone[index], start[index], arrive[index], renmark[index],cdate[2*index],"船老板");
data_list.append(tup)
data_df=data_df.append(
pd.DataFrame(
{'联系人': ["匿名"], '电话': [phone[index]], '船名': [shipname], '吨位': [tone[index]],
'始发地': [start[index]], '到达地': [arrive[index]], '起运日': [otherStyleTime],
'截运日': [otherStyleTime1], '备注': [renmark[index]],
'来源': ["船老板"]}, index=[data_df.shape[0]]),
ignore_index=True);
writer=pd.ExcelWriter(Bossship_list_filename)
data_df.to_excel(writer,engine='xlsxwriter',float_format='%.5f',index=False)
writer.save()
else:
print("获取地址失败")
return;
#查看响应内容,response.content返回的字节流数据
print(response.content.decode('utf-8'))
#查看完整的url地址
print(response.url)
#查看响应头部字符编码
print(response.encoding)
#查看响应码
print(response.status_code)
if __name__=="__main__":
app=wx.App(False) #wx对象创建以后,相应的UI对象才能被正确初始化。
frame=MyForm()
frame.Show()
app.MainLoop() #形成消息循环。否则程序将直接退出。