快递单号批量查询Python脚本:从手动到自动化的完整实现

快递单号批量查询Python脚本:从手动复制粘贴到一键导出

前言

做电商的朋友都知道,每天要查大量快递单号。一个个手动查太慢了,今天分享一个Python脚本,实现批量查询快递单号,一键导出结果。

一、需求分析

痛点:

• 每天几百个快递单号要查

• 手动一个个复制到快递公司官网查,太慢

• 查完还要手动记录,容易出错

目标:

• 批量导入单号

• 自动查询物流状态

• 一键导出Excel

二、技术方案

2.1 选择API

快递查询有很多API:

• 快递100

• 快递鸟

• 阿里云市场的快递查询API

我选的是快递鸟API,免费版每天500次调用,够小商家用。

2.2 技术栈

• Python 3.8+

• requests:发送HTTP请求

• pandas:处理数据

• openpyxl:导出Excel

三、代码实现

3.1 申请API

先去快递鸟官网注册,获取:

• EBusinessID

• AppKey

免费版每天500次调用,够小商家用。

3.2 完整代码

import requests

import pandas as pd

import time

import hashlib

import base64

import json

class KdNiaoAPI:

def init(self, e_business_id, app_key):

self.e_business_id = e_business_id

self.app_key = app_key

self.url = "https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx"

def encrypt_params(self, request_data):

"""加密参数"""

param = {

"RequestData": json.dumps(request_data, ensure_ascii=False),

"EBusinessID": self.e_business_id,

"RequestType": "8001", # 即时查询

"DataType": "2",

"DataSign": self._data_sign(request_data)

}

return param

def _data_sign(self, request_data):

"""生成签名"""

string = json.dumps(request_data, ensure_ascii=False) + self.app_key

md5 = hashlib.md5(string.encode('utf-8'))

return base64.b64encode(md5.digest()).decode('utf-8')

def query(self, logistic_code, shipper_code="ZTO"):

"""

查询快递

:param logistic_code: 快递单号

:param shipper_code: 快递公司编码(ZTO=中通, YTO=圆通, STO=申通, YD=韵达)

"""

request_data = {

"OrderCode": "",

"ShipperCode": shipper_code,

"LogisticCode": logistic_code

}

param = self.encrypt_params(request_data)

try:

response = requests.post(self.url, data=param, timeout=10)

result = response.json()

if result.get("Success"):

return {

"success": True,

"logistic_code": logistic_code,

"state": result.get("State"),

"traces": result.get("Traces", \[\])

}

else:

return {

"success": False,

"logistic_code": logistic_code,

"reason": result.get("Reason", "查询失败")

}

except Exception as e:

return {

"success": False,

"logistic_code": logistic_code,

"reason": str(e)

}

def batch_query(input_excel, output_excel):

"""

批量查询快递单号

:param input_excel: 输入Excel(包含单号列)

:param output_excel: 输出Excel

"""

读取输入文件

df = pd.read_excel(input_excel)

初始化API

api = KdNiaoAPI(

e_business_id="你的EBusinessID",

app_key="你的AppKey"

)

results = \[\]

for index, row in df.iterrows():

logistic_code = str(row'快递单号')

shipper_code = row.get('快递公司', 'ZTO') # 默认中通

print(f"正在查询: {logistic_code}")

result = api.query(logistic_code, shipper_code)

if result"success":

取最新一条物流信息

traces = result"traces"

latest_trace = traces0"AcceptStation" if traces else "无物流信息"

trace_time = traces0"AcceptTime" if traces else ""

results.append({

"快递单号": logistic_code,

"状态": result"state",

"最新物流": latest_trace,

"更新时间": trace_time

})

else:

results.append({

"快递单号": logistic_code,

"状态": "查询失败",

"最新物流": result"reason",

"更新时间": ""

})

避免请求太快,加延时

time.sleep(0.5)

导出结果

result_df = pd.DataFrame(results)

result_df.to_excel(output_excel, index=False)

print(f"查询完成,结果已导出到: {output_excel}")

if name == "main":

batch_query(

input_excel="快递单号列表.xlsx",

output_excel="查询结果.xlsx"

)

四、使用方法

4.1 准备输入文件

准备一个Excel文件,包含两列:

• 快递单号

• 快递公司(可选,默认中通)

示例:

| 快递单号 | 快递公司 |

|---|---|

| 73123456789012 | ZTO |

| 73123456789013 | YTO |

| 73123456789014 | STO |

4.2 运行脚本

python kd_query.py

4.3 查看结果

运行完会生成一个`查询结果.xlsx`,包含:

• 快递单号

• 状态

• 最新物流

• 更新时间

五、优化建议

5.1 批量查询优化

如果单号很多(几百上千个),可以用多线程:

from concurrent.futures import ThreadPoolExecutor

def batch_query_multithread(input_excel, output_excel, max_workers=5):

df = pd.read_excel(input_excel)

api = KdNiaoAPI("你的ID", "你的Key")

results = \[\]

with ThreadPoolExecutor(max_workers=max_workers) as executor:

futures = \[\]

for index, row in df.iterrows():

future = executor.submit(

api.query,

str(row'快递单号'),

row.get('快递公司', 'ZTO')

)

futures.append(future)

for future in futures:

results.append(future.result())

导出结果...

5.2 错误重试

网络请求可能失败,加重试机制:

import time

def query_with_retry(api, logistic_code, shipper_code, max_retries=3):

for i in range(max_retries):

result = api.query(logistic_code, shipper_code)

if result"success":

return result

time.sleep(1) # 等1秒再试

return result

5.3 缓存结果

已经查过的单号,缓存起来,避免重复查询:

import json

def load_cache(cache_file):

try:

with open(cache_file, 'r') as f:

return json.load(f)

except:

return {}

def save_cache(cache, cache_file):

with open(cache_file, 'w') as f:

json.dump(cache, f, ensure_ascii=False)

六、实际使用体验

我用这个脚本查快递单号,对比手动查:

| 方式 | 100个单号耗时 | 出错率 |

|---|---|---|

| 手动查 | 2小时 | 5% |

| 脚本查 | 1分钟 | 0% |

效率提升120倍,还不会出错。

七、 alternatives

如果不想自己写代码,也有现成的工具:

固乔快递查询助手

• 不用写代码,界面操作

• 支持批量导入导出

• 48元/天,168元/月,1288元/年

• 适合不会编程的商家

对比:

• 自己写脚本:免费,但要会编程

• 固乔快递助手:付费,但开箱即用

结尾FAQ

Q:快递查询API免费吗?

A:快递鸟免费版每天500次调用,够小商家用。量大了要付费。

Q:这个脚本支持哪些快递公司?

A:支持中通、圆通、申通、韵达、顺丰等主流快递公司。

Q:不会编程能用吗?

A:不会编程可以用固乔快递查询助手,界面操作,开箱即用。

Q:批量查询1000个单号要多久?

A:用多线程,大概5-10分钟。手动查要一整天。

Q:查询结果准确吗?

A:API直接对接快递公司,数据是实时的,准确。


*本文基于实际电商场景整理,代码仅供参考。具体API参数以官方文档为准。*

相关推荐
人工智能导论实践课1 小时前
【GUI桌面开发3】PyCharm配置外部工具
ide·python·pycharm
一千柯橘1 小时前
LangChain 的实时输出处理: stream_events 和 Streaming
python·langchain·agent
贾公子1 小时前
图片 AIGC 检测接入实战——URL 与 Base64 的取舍、体积校验与「你送过去的可能不是那张图」
python·aigc
天远Date Lab1 小时前
零信任架构实战:基于天远企业年报信息核验构建自动化商业保理财务与社保穿透评估网关
人工智能·架构·自动化
@大迁世界2 小时前
告别 Go,拥抱 Rust
开发语言·golang·rust
SEO_juper2 小时前
Node.js 重定向链检测工具:301 跳了几跳、有没有成环,一次看清
xml·开发语言·python·node.js·json·bash
学逆向的2 小时前
C 指针常量与常量指针
c语言·开发语言·网络安全
codezzzsleep2 小时前
学术汇报 PPT 自动化生成实战指南
运维·自动化·powerpoint
曲径海盗2 小时前
【Python 学习第 37 天】for 循环
python·学习笔记·编程入门