快递单号批量查询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 小时前
python小工具win7翻车事故现场
python
pps-key3 小时前
网络攻防入门:从“黑客梦”到合法实操(生存篇)
开发语言·web安全·php
汤姆宝库3 小时前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
岁月宁静3 小时前
从零拆解 AI 语音模拟面试系统
人工智能·python·agent
benchmark_cc3 小时前
个人开发者接入五档盘口:用 QuantDash 读取单只股票的验收清单与易错点
python·数据分析·pandas·量化交易·股票数据·quantdash
ZhengEnCi5 小时前
项目越写越乱?先别改架构:用一次目录重排 + 一份可复算的体检脚本把乱治住
python·架构·ai编程
驭渊的小故事5 小时前
订单服务如何调用商品服务?一次 RestTemplate 跨服务调用入门
java·开发语言·php
Dmz丶5 小时前
前端转 AI 100 天 Day 45:阶段复盘——从“会调 API”到“做出 AI 产品”
python
Sakura_j_h_6 小时前
MCP SDK 2.0 实战:用 MCPServer 搭本地笔记检索服务
开发语言·笔记·python·qt·ai工具·mcp·mcpserver
微笑星河q6 小时前
C++STL【vector】常用接口函数使用和迭代器失效问题
开发语言·c++