学了大概两个月的Python之后,今天突然来个灵感想写一个可以自动识别快递单号并能查询物流信息的程序!
功能界面如下图所示,只需要输入正常的快递单号然后回车,就能查询到物流信息.
首先我们的Python需要安装requests_html模块, 安装方法 pip install requests_html 这个模块必须要安装,否则运行本程序就会报错.
这里调用的API接口是快递100的 http://www.kuaidi100.com/
首先我们需要正确的识别出快递单号是哪一家物流公司的,代码如下
这里是用sb函数封装起来了,供下面的查询物流信息函数调用.
这样通过get获取的数据都是json格式的,我们这里可以直接json()来解析,因为requests_html 模块自带了, 所以不需要重新的再 import 了 !
最后框架写好了,直接就可以调用函数了,代码如下:
from requests_html import HTMLSession
session = HTMLSession()
def sb(dh):
'''用来识别快递 返回快递种类!'''
url = 'http://www.kuaidi100.com/autonumber/autoComNum?resultv2=1&text=' + dh
header = {
'Referer': 'http://www.kuaidi100.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest'
}
r = session.get(url, headers=header)
r = r.json()
return r['auto'][0]['comCode']
def kuaidi100(dh):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
}
url = 'http://www.kuaidi100.com/query'
data = {
'type': sb(dh),
'postid': dh,
'temp': '0.916395518853228'
}
r = session.get(url, params=data)
r = r.json()
#print(r)
for x in r['data']:
print(x['ftime'] + '-' * 7 + x['context'])
if __name__ == '__main__':
print('*' * 20 + '在线实时快递查询系统' + '*' * 20)
dh = str(input('请输入快递单号:'))
kuaidi100(dh)
本教程非常适合刚学习Python的小伙伴,用到的模块也非常的少,有能力的还可以优化下程序,还可以打包成exe文件哦!
向大佬低头,抱住大腿
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
不是大佬,只不过是愿意多花点时间学习! 学无止境
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Congratulations @centos! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :
Click here to view your Board of Honor
If you no longer want to receive notifications, reply to this comment with the word
STOP
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit