使用urllib库实现快递单号查询
时间: 2024-05-12 16:14:53 浏览: 23
可以使用快递100的API来实现快递单号查询。以下是使用Python的urllib库实现的示例代码:
```python
import urllib.request
import json
# 快递100 API地址和参数
url = 'https://www.kuaidi100.com/query'
params = {
'type': '快递公司类型',
'postid': '快递单号'
}
# 拼接完整的URL
url += '?' + urllib.parse.urlencode(params)
# 发送请求并获取响应
response = urllib.request.urlopen(url)
content = response.read().decode('utf-8')
# 解析JSON格式的响应
data = json.loads(content)
# 输出快递信息
if data['status'] == '200':
for item in data['data']:
print(item['time'], item['context'])
else:
print(data['message'])
```
其中,需要替换掉`type`和`postid`参数为对应的快递公司类型和快递单号。另外,由于快递100 API返回的是JSON格式的响应,需要使用`json`模块解析响应内容。
相关问题
使用urllib库实现快递单号查询 Ø百度中搜索“快递单号查询” Ø选择快递公司,输入快递单号,查询 Ø物流信息以时间倒序的方式展示:时间+物流状态
以下是使用urllib库实现快递单号查询的代码:
```python
import urllib.request
import json
# 输入快递单号和快递公司名称
express_number = input("请输入快递单号:")
express_company = input("请输入快递公司名称:")
# 拼接快递查询的url
url = "https://www.kuaidi100.com/query?type=" + express_company + "&postid=" + express_number
# 发送GET请求
response = urllib.request.urlopen(url)
# 将获取到的json数据转换成python对象
data = json.loads(response.read().decode())
# 判断快递信息是否获取成功
if data["status"] == "200":
print("快递公司:" + data["com"] + "\n快递单号:" + data["nu"])
print("物流信息:")
for item in data["data"]:
print(item["time"] + " " + item["context"])
else:
print("获取快递信息失败!")
```
运行上述代码后,会要求输入快递单号和快递公司名称,然后会自动获取快递信息并输出。其中,使用了urllib库发送GET请求,获取到json格式的快递信息后,解析出物流信息并按时间倒序输出。
python使用urllib库编写获取快递物流信息的算法
可以使用 `urllib` 库中的 `urlopen` 函数来获取快递物流信息。以下是一个简单的示例代码,用于从快递100网站获取顺丰快递的物流信息:
```python
import urllib.request
import json
def get_logistics_info(express_number):
url = "https://www.kuaidi100.com/query?type=sf&postid=" + express_number
response = urllib.request.urlopen(url)
content = response.read().decode('utf-8')
data = json.loads(content)
if data['status'] == '200':
for item in data['data']:
print(item['time'], item['context'])
else:
print("查询失败")
get_logistics_info("顺丰快递单号")
```
在上述代码中,我们通过 `urlopen` 函数打开了一个指定的 URL,然后读取了网页的内容,并将其解码为 UTF-8 编码的字符串。我们将返回的 JSON 数据解析为一个 Python 字典,然后遍历该字典中的所有数据项,并输出快递的时间和状态信息。在调用 `get_logistics_info` 函数时,需要将快递单号作为参数传入。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)