通過https://www.kuaidi100.com/來獲取數據
# 快遞一鍵查詢:通過https://www.kuaidi100.com/來獲取數據 import requests,random from datetime import datetime flag = True # 返回時間屬於周幾 def get_week_day(timestr): day = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S').weekday() week_day_dict = { 0: '星期一', 1: '星期二', 2: '星期三', 3: '星期四', 4: '星期五', 5: '星期六', 6: '星期天', } return week_day_dict[day] # 查詢快遞公司 def query_comCode(postid): 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.get(url, params=params, headers=headers) result = False if res.status_code == 200: json_comCode = res.json() # print(json_comCode) if 'auto' in json_comCode: if len(json_comCode['auto']) <= 0: print('快遞公司識別錯誤!請檢查快遞單號是否輸入正確!') else: # print(json_comCode['auto']) for comCode in json_comCode['auto']: # print(comCode['comCode']) # 查詢快遞進度 result = query_progress(comCode['comCode'], postid) if result: break else: print('遇到錯誤了:{}'.format(json_comCode)) else: print('查詢快遞公司:拒絕訪問!') return result # 查詢快遞進度 def query_progress(type = '', 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': str(random.random()), 'phone': '' } res = requests.get(url, params=params, headers=headers) if res.status_code == 200: json_data = res.json() # print(json_data) if json_data['status'] != '200': return False else: # print(json_data['data']) return json_data['data'] else: print('查詢快遞進度:拒絕訪問!') # 打印查詢記錄 def print_result(result): # 倒敘 result.reverse() result2 = [] pre_week_str = "" for item in result: # 獲取時間點是周幾 cur_week_str = get_week_day(item['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('{}{}:{}'.format(item['ftime'], " " + show_week_str, item['context'])) # 倒敘 result2.reverse() for item in result2: print(item) 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_comCode(postid) if result: print_result(result) else: print('抱歉,暫無查詢記錄') again() print('感謝使用,程序已退出!') main()