希望你拼命爭取的,最後都能如你所願。
快遞100網站可以很方便的查詢快遞的物流資訊
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
import cv2 as cv
# 根據快遞單號查詢物流資訊
def get_screenshot_and_info():
chrome_driver = r'D:\python\pycharm2020\chromedriver.exe' # chromedriver的路徑
options = webdriver.ChromeOptions()
# 關閉左上方 Chrome 正受到自動測試軟體的控制的提示
options.add_experimental_option('useAutomationExtension', False)
options.add_experimental_option("excludeSwitches", ['enable-automation'])
# 開啟瀏覽器物件
browser = webdriver.Chrome(options=options, executable_path=chrome_driver)
# 存取這個url
browser.get('https://www.kuaidi100.com/')
# 顯示等待
wait = WebDriverWait(browser, 5)
wait.until(ec.presence_of_element_located((By.ID, 'menu-track')))
# 視窗最大化
browser.maximize_window()
browser.find_element_by_name('postid').send_keys(nums)
browser.find_element_by_id('query').click()
time.sleep(1)
browser.find_element_by_id('query').click()
time.sleep(2)
browser.execute_script("window.scrollBy(0, 488)")
# 截圖
browser.get_screenshot_as_file(filename='info.png')
items = browser.find_elements_by_xpath('//table[@class="result-info"]/tbody/tr')
print('物流資訊查詢結果如下:\n')
for item in items:
time_ = item.find_element_by_xpath('.//td[1]').text.replace('\n', ' ')
contex = item.find_element_by_xpath('.//td[3]').text
print(f'時間:{time_}')
print(f'狀態:{contex}\n')
browser.quit()
# 顯示截圖
src = cv.imread(filename='info.png')
src = cv.resize(src, None, fx=0.7, fy=0.7)
cv.imshow('result', src)
cv.waitKey(0)
if __name__ == '__main__':
nums = input('請輸入您的單號:')
print('\n')
get_screenshot_and_info()
執行效果如下:
import requests
import json
def query_info(i, j):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24',
"Referer": "https://www.kuaidi100.com/"
}
url = f'https://www.kuaidi100.com/query?type={j}&postid={i}&temp=0.53162373256954096&phone='
resp = requests.get(url, headers=headers)
# print(resp.text)
datas = json.loads(resp.text)['data']
# print(datas)
print('您的快遞物流資訊查詢結果如下:\n')
for item in datas:
time_ = item['time']
info = item['context']
print(f'時間:{time_}')
print(f'物流狀態:{info}' + '\n')
if __name__ == '__main__':
delivery_dic = {
'圓通': 'yuantong', '申通': 'shentong', '中通': 'zhongtong', '百世快遞': 'huitongkuaidi',
'韻達': 'yunda', '順豐': 'shunfeng', '天天快遞': 'tiantian', '郵政': 'youzhengguonei',
'EMS': 'ems', '京東': 'jd', '德邦快遞': 'debangwuliu', '極兔快遞': 'jtexpress'
}
post_id = input('請輸入你要查詢物流的快遞單號:')
delivery = input('請輸入快遞公司:')
query_info(post_id, delivery_dic[delivery])
執行結果如下:
requests爬蟲查詢速度較快,但需要輸入快遞公司,便於構造介面url來請求查詢。