
import requests
import json
def get_express_type(postid):
'''根據快遞單號來智能判斷快遞類型'''
url = 'http://www.kuaidi100.com/autonumber/autoComNum?resultv2=1&text=%s' % (postid,) # 這里可以用元組這樣保證的數據的安全性
# 把構造后的url通過requests請求來得到相應的數據是一個json數據
rs = requests.get(url)
# 再用json庫中的loads數據來進行分析得到一個可用字典的方式來訪問
kd_type_info = json.loads(rs.text)
kd_type = kd_type_info['auto'][0]['comCode']
return kd_type, postid
def execute_data_query(type, postid):
'''執行數據查詢程序'''
# 通過構造一個真正的url地址
url = 'http://www.kuaidi100.com/query?type=%s&postid=%s' % (type, postid) # 這里可以用元組這樣保證的數據的安全性
# 把構造后的url通過requests請求來得到相應的數據是一個json數據
rs = requests.get(url)
# 再用json庫中的loads數據來進行分析得到一個可用字典的方式來訪問
kd_info = json.loads(rs.text)
msg = kd_info['message']
# 判斷是否成功獲取到了json的數據,如果有數據則進行下一步的解析
if msg == 'ok':
print('您的快遞%s物流信息如下:' % postid)
data = kd_info['data']
for data_dict in data:
time = data_dict['time']
context = data_dict['context']
print('時間:%s %s' % (time, context))
else:
if msg == '參數錯誤':
print('您輸入信息有誤,請重輸:')
else:
print(msg)
def main():
'''快遞查詢主程序'''
while True:
print('**歡迎您登錄快遞查詢系統**')
print('-' * 30)
print('** 1. 請輸入您的快遞單號 **')
print('** 0. 退出查詢系統 **')
print('-' * 30)
order = input('查詢請輸入1退出請輸入0:')
if order == '1':
# 進行快遞查詢操作
postid = input('請輸入您的快遞單號:')
type, postid = get_express_type(postid)
execute_data_query(type, postid)
elif order == '0':
exit()
else:
print('!!!!!您的指令輸入有誤,請重新輸入:<---------')
if __name__ == '__main__':
main()