脚本怎样批量查询物流状态

wen 实用脚本 28

本文目录导读:

脚本怎样批量查询物流状态

  1. 方案一:使用第三方聚合API(推荐,最稳定)
  2. 方案二:使用现成的开源项目(免费,有稳定性风险)
  3. 方案三:模拟浏览器/手机端爬虫(不推荐,极不稳定)
  4. 方案四:使用Excel VBA(适合非程序员)
  5. 关键问题:如何获取快递公司的编码?
  6. 推荐工作流程(最省心)

要实现批量查询物流状态,通常需要借助编程脚本(如Python)或自动化工具(如Excel VBA、RPA),由于各大快递公司(顺丰、中通、京东、菜鸟等)对API的开放程度和限制不同,最通用的方案是使用第三方物流聚合API(如快递100、菜鸟物流云)

以下是几种常见的实现方案,按推荐程度排序:

使用第三方聚合API(推荐,最稳定)

这是最正规、成功率最高的方式,你需要申请一个API Key(通常是付费或有限免费额度)。

步骤:

  1. 注册服务: 选一个聚合API平台,如:

    • 快递100(企业版/个人版)
    • 菜鸟物流云(需企业资质)
    • TrackingMore
  2. 获取API Key: 注册后拿到 keysecret

  3. 编写Python脚本:

    import requests
    import json
    import time
    # 1. 配置你的API信息(以快递100为例)
    API_KEY = "YOUR_API_KEY"  # 替换为你的key
    API_SECRET = "YOUR_SECRET"  # 替换为你的secret
    # 2. 要查询的运单列表 (格式: [(快递公司编码, 运单号), ...])
    # 常用编码: shunfeng, yuantong, zhongtong, jd, yunda, shentong
    tracking_numbers = [
        ("shunfeng", "SF123456789"),
        ("yuantong", "YT987654321"),
        ("zhongtong", "ZT555555555"),
    ]
    def query_single(company, number):
        url = "https://api.kuaidi100.com/query"
        params = {
            "key": API_KEY,
            "company": company,
            "number": number,
            "secret": API_SECRET  # 如果开启了安全验证
        }
        try:
            response = requests.post(url, data=params, timeout=10)
            data = response.json()
            if data.get("state") == "3":  # 已签收
                status = "已签收"
                detail = data["data"][0]["context"]
            elif data.get("state") == "0":
                status = "无轨迹或异常"
                detail = ""
            else:
                # 获取最新的一条物流信息
                status = data.get("state_text", "运输中")
                detail = data["data"][0]["context"] if data.get("data") else "暂无轨迹"
            return number, status, detail
        except Exception as e:
            return number, "接口调用失败", str(e)
    # 批量查询(建议带延时,避免频率限制)
    for company, number in tracking_numbers:
        result = query_single(company, number)
        print(f"运单: {result[0]} | 状态: {result[1]} | 最新: {result[2]}")
        time.sleep(0.5)  # 每查一条等0.5秒

使用现成的开源项目(免费,有稳定性风险)

如果不想付费,且查询量不大,可以使用GitHub上的开源爬虫或API封装库。

推荐:

  • kuaidi100-python (PyPI上有包)
  • trackingmore (开源API库)
  • Express-Query (GitHub搜索项目)

示例(使用trackingmore):

# 安装: pip install trackingmore
from trackingmore import TrackingMore
# 初始化客户端(需要注册获取API Key)
tm = TrackingMore('your-api-key')
# 批量创建查询任务
results = []
trackings = [
    {'tracking_number': 'YT123456789', 'courier_code': 'yuantong'},
    {'tracking_number': 'SF987654321', 'courier_code': 'shunfeng'}
]
for t in trackings:
    result = tm.trackings.create(tracking_number=t['tracking_number'], courier_code=t['courier_code'])
    results.append(result.latest_events[0].description if result.latest_events else '暂无')

模拟浏览器/手机端爬虫(不推荐,极不稳定)

适用场景: 无法获取API,且查询的快递公司网站反爬较弱。 缺点: 容易被封IP、需要识别验证码、网站改版即失效。

思路:

  1. 使用 requests + beautifulsoup4 模拟发包。
  2. 或者使用 selenium 模拟人工操作。
  3. 关键:绕过验证码(通常需要接入打码平台或OCR识别,非常麻烦)。

示例(纯粹示意,99%会失败):

# 极其不推荐,仅供了解原理
import requests
# url = f"https://www.kuaidi100.com/query?type=zhongtong&postid=YT12345"
# 这种请求往往需要加密签名,直接请求很难成功。

使用Excel VBA(适合非程序员)

如果你不想安装Python,且数据在Excel里,可以用VBA调用公共API。

步骤:

  1. 打开Excel → Alt + F11 打开VBA编辑器。
  2. 插入模块,粘贴代码(需要先启用 Microsoft XML, v6.0 引用)。

简单VBA示例(调用快递100免签公共接口,稳定性低):

Function GetTracking(number As String, company As String) As String
    ' 这里是伪代码,公共接口现在基本都失效或限制了
    Dim http As Object
    Set http = CreateObject("MSXML2.XMLHTTP")
    Dim url As String
    url = "https://api.kuaidi100.com/query?type=" & company & "&postid=" & number
    http.Open "GET", url, False
    http.send
    GetTracking = http.responseText
End Function

关键问题:如何获取快递公司的编码?

你需要将中文名(如“圆通快递”)映射为API识别的英文编码(如 yuantong)。 常见快递编码表(通用API标准):

快递公司 API编码
顺丰 shunfeng
圆通 yuantong
中通 zhongtong
韵达 yunda
申通 shentong
京东快递 jd
邮政EMS ems
德邦 debangkuaidi
极兔速递 jtexpress

推荐工作流程(最省心)

  1. 小规模(<100单/天): 使用免费的 TrackingMore 开源库(注册免费API Key,有月度限制)。
  2. 中规模(<1000单/天): 购买 快递100 企业版API(按次计费)。
  3. 超大规模(>10000单/天): 直接对接菜鸟物流云(需电商平台资质)。

无论如何,请不要尝试去爬取快递100或菜鸟官网的网页,它们的风控系统会立刻拦截你的IP。 直接使用正规API是唯一稳定可靠的方案。

抱歉,评论功能暂时关闭!