目录
(3)编写logistics_info_analysis.py
1.介绍
本篇文章将介绍使用Python调用快递100的API实现快递信息的查询,您也可以访问我的主页查看其他文章:
2.准备工作
(1)快递100企业管理后台
https://api.kuaidi100.com/manager/page/myinfo/enterprise
注册并登录账号成为测试账号.
(2)查看接口文档
(3)获取调用权限
这里我们需要用到的是授权key和customer,还需确认已开通实时查询.
3.代码实现
(1)项目结构
(2) 编写logistics_info.py
import hashlib
import json
import requests
# 授权信息可通过链接查看:https://api.kuaidi100.com/manager/page/myinfo/enterprise
class LogisticsInfo():
def __init__(self, num, com):
self.key = '换成你的key' # 客户授权key
self.customer = '换成你的customer' # 查询公司customer编号
self.com = com # 快递公司
self.num = num # 快递单号
def logistics(self):
param = {
'com': self.com, # 查询的快递公司的编码,一律用小写字母
'num': self.num, # 查询的快递单号,单号的最大长度是32个字符
'phone': '', # 收件人或寄件人的手机号或固话(也可以填写后四位,如果是固话,请不要上传分机号)
'from': '', # 出发地城市,省-市-区,非必填,填了有助于提升签收状态的判断的准确率,请尽量提供
'to': '', # 目的地城市,省-市-区,非必填,填了有助于提升签收状态的判断的准确率,且到达目的地后会加大监控频率,请尽量提供
'resultv2': '4', # 添加此字段表示开通行政区域解析功能。0:关闭(默认),1:开通行政区域解析功能,4:开通行政解析功能并且返回出发、目的及当前城市信息
'show': '0', # 返回数据格式。0:json(默认),1:xml,2:html,3:text
'order': 'desc' # 返回结果排序方式。desc:降序(默认),asc:升序
}
pjson = json.dumps(param) # 转json字符串
postdata = {
'customer': self.customer, # 查询公司customer 编号
'param': pjson # 参数数据
}
# 签名加密, 用于验证身份, 按param + key + customer 的顺序进行MD5加密(注意加密后字符串要转大写), 不需要“+”号
str = pjson + self.key + self.customer
md = hashlib.md5()
md.update(str.encode())
sign = md.hexdigest().upper()
postdata['sign'] = sign # 加密签名
url = 'http://poll.kuaidi100.com/poll/query.do' # 实时查询请求地址
result = requests.post(url, postdata) # 发送请求
result = json.loads(result.text)
# print(type(result))
# print(result)
with open('../data/wuliu.json', 'w', encoding='utf-8') as f:
json.dump(result, f, ensure_ascii=False, indent=2)
return result
(3)编写logistics_info_analysis.py
import datetime
class LogisticsInfoAnalysis():
def __init__(self, logistics_info):
self.logistics_info = logistics_info
def logistics_info_analysis(self):
times = []
print('*'*100)
print(f'快递单号:{self.logistics_info["nu"]}')
print(f'快递公司:{self.logistics_info["com"]}')
print('*'*100)
print("物流跟踪信息:")
for item in self.logistics_info['data']:
times.append(item['time'])
print(item['time'], item['context'])
time_str1 = times[-1] # 物流开始时间
time_str2 = times[0] # 物流结束时间
time1 = datetime.datetime.strptime(time_str1, '%Y-%m-%d %H:%M:%S')
time2 = datetime.datetime.strptime(time_str2, '%Y-%m-%d %H:%M:%S')
diff = time2 - time1
total_seconds = diff.total_seconds()
# 计算天数、小时数、分钟数和秒数
days, seconds = divmod(total_seconds, 86400)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
print('*'*100)
# 格式化输出
print(f'这个快递的物流总耗时 {int(days)} 天 {int(hours)} 时 {int(minutes)} 分 {int(seconds)} 秒')
print('*'*100)
(4) 编写test.py
from logistics_info import LogisticsInfo
from logistics_info_analysis import LogisticsInfoAnalysis
if __name__ == '__main__':
num = '7835562143****' # 快递单号
com = 'zhongtong' # 快递公司
info = LogisticsInfo(num, com).logistics() # 物流信息
# print(test)
LogisticsInfoAnalysis(info).logistics_info_analysis() # 分析并输出物流信息
注意事项:
可在快递100官网下载快递公司编码:
4.测试
(1)运行test.py
(2)查看wuliu.json
在data/wuliu.json中也保存了调用API获取到的数据: