1.使用快递100网站批量查询物流信息;
官方网址:快递100-查快递,寄快递,上快递100 (kuaidi100.com)
2.只写了三种快递的爬取;
3.Selenium主要是简单,小规模数据时可用;
4.输入为快递单号表格;
5.需要安装对应的浏览器驱动;
import pandas as pd
from bs4 import BeautifulSoup
import requests
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
# 步骤1:读取表格中的快递单号数据
# 假设你的表格文件名为 'express_data.xlsx',并且包含一个名为 '快递单号' 的列
data = pd.read_excel('express_data.xlsx')
# 设置Edge WebDriver的路径,根据你的实际路径进行替换
edge_driver_path = 'edgedriver.exe'
# 启动Edge浏览器
driver = webdriver.Edge(executable_path=edge_driver_path)
# 打开网站
driver.get('https://www.kuaidi100.com/')
def get_message(company_code,postid):
# 刷新页面
driver.refresh()
# 找到输入框并输入订单号
input_box = driver.find_element(By.ID, 'input')
# 清空输入框内容
#input_box.clear()
input_box.send_keys(postid)
# 选择快递
express_choice = driver.find_element(By.ID, 'comIcon')
express_choice.click()
# 选择要点击的快递元素
selected_element = driver.find_element(By.CSS_SELECTOR, f'a[data-code="{company_code}"]')
time.sleep(0.3)
# 等待元素可见和可交互
#element = WebDriverWait(driver, 0.3).until(
# EC.element_to_be_clickable((By.CSS_SELECTOR, f'a[data-code="{company_code}"]'))
#)
# 执行点击操作
#element.click()
selected_element.click()
time.sleep(0.5)
#刷新界面
new_page_response = driver.page_source
# 将页面响应传递给Beautiful Soup进行解析
soup = BeautifulSoup(new_page_response, 'html.parser')
# 选择包含所需信息的所有<li>元素
steps = soup.find_all('li', class_='step')
logistics_info = ""
# 遍历每个步骤,提取所需的信息
for step in steps:
datetime = step.find('div', class_='datetime').get_text()
text = step.find('div', class_='text').get_text()
# 拼接时间和物流信息
logistics_info += f"时间: {datetime}\t{text}\n"
# 打印所有的物流信息
print(logistics_info)
return logistics_info
num=1
message_list=[]
for tracking_number in data['快递单号']:
postid = str(tracking_number)
if postid.startswith('JT'):#极兔
company_code = "jtexpress"
elif postid.startswith('9'):
company_code = "youzhengguonei"#邮政
elif postid.startswith('7'):
company_code = "shentong"#申通
else:
company_code =input("输入快递公司:")
print(f'第{num}个:快递单号: {tracking_number}')
num=num+1
message=get_message(company_code, postid)
message_list.append(message)
#写入表格:
data['物流信息'] = message_list
# 将 DataFrame 保存为表格
data.to_csv('output_table.csv', index=False) # 也可以选择其他格式,如 Excel 格式 .xlsx
# 如果要保存到 Excel 格式
#data.to_excel('output_table.xlsx', index=False)
# 关闭浏览器
driver.quit()
print('-------------------over--------------------')