溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python如何爬取快遞100能查詢的物流信息

發布時間:2021-10-26 09:42:46 來源:億速云 閱讀:454 作者:柒染 欄目:大數據
# Python如何爬取快遞100能查詢的物流信息

## 前言

在電商和物流行業蓬勃發展的今天,物流信息的實時查詢成為剛需??爝f100作為國內知名的物流信息聚合平臺,提供了豐富的API接口供開發者調用。本文將詳細介紹如何使用Python爬取快遞100的物流信息,涵蓋從基礎API調用到高級反反爬策略的完整解決方案。

---

## 一、準備工作

### 1.1 注冊快遞100開發者賬號
訪問[快遞100開放平臺](https://api.kuaidi100.com/)完成注冊,獲取以下關鍵信息:
- CustomerID(企業ID)
- API Key(接口密鑰)

### 1.2 安裝必備Python庫
```bash
pip install requests pandas hashlib json time random

1.3 接口文檔概覽

快遞100提供兩種主要接口: - 實時查詢API(免費版有QPS限制) - 訂閱推送API(適合大規模查詢)


二、基礎API調用實現

2.1 實時查詢接口

import requests
import hashlib
import json

def query_express(customer, key, com, num):
    url = "https://poll.kuaidi100.com/poll/query.do"
    
    # 構造請求參數
    param = {
        "com": com,        # 快遞公司代碼
        "num": num,       # 快遞單號
        "phone": ""        # 收/寄件人手機號(部分快遞需要)
    }
    
    # 生成簽名
    sign_str = json.dumps(param) + key + customer
    sign = hashlib.md5(sign_str.encode()).hexdigest().upper()
    
    payload = {
        "customer": customer,
        "sign": sign,
        "param": json.dumps(param)
    }
    
    headers = {'Content-Type': "application/x-www-form-urlencoded"}
    response = requests.post(url, data=payload, headers=headers)
    return response.json()

# 使用示例
result = query_express(
    customer="YOUR_CUSTOMER_ID",
    key="YOUR_API_KEY",
    com="yuantong",  # 圓通快遞代碼
    num="YT123456789"
)
print(result)

2.2 返回數據結構解析

典型響應示例:

{
    "message": "ok",
    "state": "3",
    "status": "200",
    "data": [
        {
            "time": "2023-05-01 08:00:00",
            "context": "已簽收,感謝使用圓通速遞",
            "location": ""
        },
        {
            "time": "2023-04-30 15:30:00",
            "context": "[杭州市] 浙江杭州濱江公司派件員:張三(138****1234)正在為您派件",
            "location": "杭州"
        }
    ]
}

關鍵字段說明: - state: 物流狀態(0-在途,1-攬收,2-疑難,3-簽收,4-退簽) - data: 物流軌跡數組(按時間倒序排列)


三、高級應用技巧

3.1 自動識別快遞公司

當不確定快遞公司時,使用智能識別接口:

def auto_detect_company(key, num):
    url = f"https://www.kuaidi100.com/autonumber/auto?num={num}&key={key}"
    response = requests.get(url)
    return response.json()  # 返回可能的快遞公司列表

3.2 多單號批量查詢

import pandas as pd

def batch_query(orders):
    results = []
    for order in orders:
        try:
            res = query_express(**order)
            res['訂單號'] = order['num']
            results.append(res)
        except Exception as e:
            print(f"查詢失敗 {order['num']}: {str(e)}")
    return pd.DataFrame(results)

3.3 數據持久化存儲

import sqlite3

def save_to_db(data):
    conn = sqlite3.connect('express.db')
    c = conn.cursor()
    
    # 創建表(如果不存在)
    c.execute('''CREATE TABLE IF NOT EXISTS logistics
                 (id INTEGER PRIMARY KEY AUTOINCREMENT,
                  order_no TEXT,
                  status TEXT,
                  update_time TEXT,
                  context TEXT)''')
    
    # 插入數據
    for item in data['data']:
        c.execute("INSERT INTO logistics VALUES (NULL,?,?,?,?)",
                 (data['num'], data['state'], item['time'], item['context']))
    
    conn.commit()
    conn.close()

四、反反爬策略實戰

4.1 請求頭偽裝

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Referer': 'https://www.kuaidi100.com/',
    'Origin': 'https://www.kuaidi100.com'
}

4.2 請求頻率控制

import time
import random

def safe_query(params):
    delay = random.uniform(1.2, 3.5)  # 隨機延遲
    time.sleep(delay)
    return query_express(**params)

4.3 代理IP池實現

proxy_list = [
    "http://112.85.164.220:9999",
    "http://117.69.201.148:9999"
]

def rotate_proxy_request(url, params):
    proxy = {"http": random.choice(proxy_list)}
    return requests.post(url, proxies=proxy, **params)

五、異常處理與日志記錄

5.1 常見異常類型

  • 429錯誤:請求過于頻繁
  • 601錯誤:單號不存在
  • 600錯誤:參數錯誤

5.2 健壯性增強代碼

import logging

logging.basicConfig(filename='express.log', level=logging.INFO)

def robust_query(params):
    try:
        result = query_express(**params)
        if result.get('status') != '200':
            raise Exception(result.get('message', 'Unknown error'))
        return result
    except requests.exceptions.RequestException as e:
        logging.error(f"Request failed: {str(e)}")
    except Exception as e:
        logging.error(f"API error: {str(e)}")
    return None

六、完整項目示例

6.1 項目結構

/express-tracker
│── config.py       # 存儲API密鑰
│── tracker.py      # 核心查詢邏輯
│── utils.py        # 工具函數
│── main.py         # 主程序入口
└── requirements.txt

6.2 主程序實現

# main.py
from tracker import batch_query
from utils import load_orders, save_results

if __name__ == "__main__":
    orders = load_orders("orders.csv")  # 從CSV加載待查詢單號
    results = batch_query(orders)
    save_results(results, "output.xlsx")
    print(f"成功查詢 {len(results)} 條物流信息")

七、法律與道德注意事項

  1. 遵守平臺規則:嚴格遵循快遞100的API使用條款
  2. 數據使用限制:不得將數據用于商業售賣等違規用途
  3. 查詢頻率控制:免費版限制為每分鐘5次請求
  4. 用戶隱私保護:妥善處理包含個人信息的物流數據

結語

通過本文介紹的方法,您可以構建一個功能完善的物流信息查詢系統。建議在實際應用中: 1. 使用異步IO提高查詢效率(如aiohttp) 2. 考慮使用官方推薦的訂閱推送模式 3. 重要業務場景建議購買企業版API服務

完整代碼示例已上傳GitHub:[示例倉庫鏈接](此處替換為實際地址) “`

(注:實際字數約2180字,可根據需要調整細節部分)

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女