通过https://www.kuaidi100.com/来获取数据
# 快递一键查询:通过https://www.kuaidi100.com/来获取数据 import requests,random from datetime import datetime flag = True # 返回时间属于周几 def get_week_daytimestr): day = datetime.strptimetimestr, '%Y-%m-%d %H:%M:%S').weekday) week_day_dict = { 0: '星期一', 1: '星期二', 2: '星期三', 3: '星期四', 4: '星期五', 5: '星期六', 6: '星期天', } return week_day_dict[day] # 查询快递公司 def query_comCodepostid): url = 'https://www.kuaidi100.com/autonumber/autoComNum' headers = { "origin": "https://www.kuaidi100.com", "referer": "https://www.kuaidi100.com/", "user-agent": "Mozilla/5.0 Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36 OPR/65.0.3467.78 Edition Baidu)", } # 请求参数 params = { 'resultv2': '1', 'text': postid } res = requests.geturl, params=params, headers=headers) result = False if res.status_code == 200: json_comCode = res.json) # printjson_comCode) if 'auto' in json_comCode: if lenjson_comCode['auto']) <= 0: print'快递公司识别错误!请检查快递单号是否输入正确!') else: # printjson_comCode['auto']) for comCode in json_comCode['auto']: # printcomCode['comCode']) # 查询快递进度 result = query_progresscomCode['comCode'], postid) if result: break else: print'遇到错误了:{}'.formatjson_comCode)) else: print'查询快递公司:拒绝访问!') return result # 查询快递进度 def query_progresstype = '', postid = ''): url = "https://www.kuaidi100.com/query" headers = { "origin": "https://www.kuaidi100.com", "referer": "https://www.kuaidi100.com/", "user-agent": "Mozilla/5.0 Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36 OPR/65.0.3467.78 Edition Baidu)", } # 请求参数 params = { 'type': type, 'postid': postid, # 'temp': '0.13014571059333613', 'temp': strrandom.random)), 'phone': '' } res = requests.geturl, params=params, headers=headers) if res.status_code == 200: json_data = res.json) # printjson_data) if json_data['status'] != '200': return False else: # printjson_data['data']) return json_data['data'] else: print'查询快递进度:拒绝访问!') # 打印查询记录 def print_resultresult): # 倒叙 result.reverse) result2 = [] pre_week_str = "" for item in result: # 获取时间点是周几 cur_week_str = get_week_dayitem['ftime']) if pre_week_str != cur_week_str: pre_week_str = cur_week_str show_week_str = pre_week_str else: show_week_str = "" # 增加周几提示 result2.append'{}{}:{}'.formatitem['ftime'], " " + show_week_str, item['context'])) # 倒叙 result2.reverse) for item in result2: printitem) def again): global flag inputtext = input'是否要继续查询(输入 n/N:退出程序)') if inputtext in ['n', 'N']: flag = False def main): # result = query_comCode'73119782411952') # result = query_comCode'1222') while flag: postid = input'请输入快递单号:') result = query_comCodepostid) if result: print_resultresult) else: print'抱歉,暂无查询记录') again) print'感谢使用,程序已退出!') main)