Python query express information

Table of contents

1 Introduction

2. Preparations

(1) Express 100 enterprise management background

(2) View interface documents

(3) Obtain call permission

3. Code implementation

(1) Project structure

(2) Write logistics_info.py

(3) Write logistics_info_analysis.py

(4) Write test.py

4. Test

(1) run test.py

(2) View wuliu.json


1 Introduction

         This article will introduce the use of Python to call the API of Express 100 to query express information. You can also visit my homepage to view other articles:

I can't finish writing code. I can't finish writing code. I'm good at Python projects, python crawlers, python operation files, etc. I can't finish writing code. I pay attention to pandas, python, django, pygame, spark, pip, virtualenv, numpy, flask fields. https : //blog.csdn.net/spx_0108         Not much to say, let's start!

2. Preparations

(1) Express 100 enterprise management background

https://api.kuaidi100.com/manager/page/myinfo/enterprise

Register and log in to your account to become a test account.

(2) View interface documents

Real-time express query interface technical documentation - express 100API open platform (kuaidi100.com)

(3) Obtain call permission

What we need to use here is the authorization key and customer , and we need to confirm that real-time query has been activated.

3. Code implementation

(1) Project structure

(2) Write logistics_info.py

import hashlib
import json
import requests

# 授权信息可通过链接查看:https://api.kuaidi100.com/manager/page/myinfo/enterprise

class LogisticsInfo():

    def __init__(self, num, com):
        self.key = '换成你的key'  # 客户授权key
        self.customer = '换成你的customer'  # 查询公司customer编号
        self.com = com  # 快递公司
        self.num = num  # 快递单号

    def logistics(self):
        param = {
            'com': self.com,  # 查询的快递公司的编码,一律用小写字母
            'num': self.num,  # 查询的快递单号,单号的最大长度是32个字符
            'phone': '',  # 收件人或寄件人的手机号或固话(也可以填写后四位,如果是固话,请不要上传分机号)
            'from': '',  # 出发地城市,省-市-区,非必填,填了有助于提升签收状态的判断的准确率,请尽量提供
            'to': '',  # 目的地城市,省-市-区,非必填,填了有助于提升签收状态的判断的准确率,且到达目的地后会加大监控频率,请尽量提供
            'resultv2': '4',  # 添加此字段表示开通行政区域解析功能。0:关闭(默认),1:开通行政区域解析功能,4:开通行政解析功能并且返回出发、目的及当前城市信息
            'show': '0',  # 返回数据格式。0:json(默认),1:xml,2:html,3:text
            'order': 'desc'  # 返回结果排序方式。desc:降序(默认),asc:升序
        }

        pjson = json.dumps(param)  # 转json字符串

        postdata = {
            'customer': self.customer,  # 查询公司customer 编号
            'param': pjson  # 参数数据
        }

        # 签名加密, 用于验证身份, 按param + key + customer 的顺序进行MD5加密(注意加密后字符串要转大写), 不需要“+”号
        str = pjson + self.key + self.customer
        md = hashlib.md5()
        md.update(str.encode())
        sign = md.hexdigest().upper()
        postdata['sign'] = sign  # 加密签名

        url = 'http://poll.kuaidi100.com/poll/query.do'  # 实时查询请求地址

        result = requests.post(url, postdata)  # 发送请求
        result = json.loads(result.text)
        # print(type(result))
        # print(result)
        with open('../data/wuliu.json', 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)

        return result

(3) Write logistics_info_analysis.py

import datetime

class LogisticsInfoAnalysis():
    def __init__(self, logistics_info):
        self.logistics_info = logistics_info

    def logistics_info_analysis(self):
        times = []
        print('*'*100)
        print(f'快递单号:{self.logistics_info["nu"]}')
        print(f'快递公司:{self.logistics_info["com"]}')
        print('*'*100)
        print("物流跟踪信息:")
        for item in self.logistics_info['data']:
            times.append(item['time'])
            print(item['time'], item['context'])


        time_str1 = times[-1]   # 物流开始时间
        time_str2 = times[0]   # 物流结束时间

        time1 = datetime.datetime.strptime(time_str1, '%Y-%m-%d %H:%M:%S')
        time2 = datetime.datetime.strptime(time_str2, '%Y-%m-%d %H:%M:%S')

        diff = time2 - time1
        total_seconds = diff.total_seconds()

        # 计算天数、小时数、分钟数和秒数
        days, seconds = divmod(total_seconds, 86400)
        hours, seconds = divmod(seconds, 3600)
        minutes, seconds = divmod(seconds, 60)

        print('*'*100)
        # 格式化输出
        print(f'这个快递的物流总耗时 {int(days)} 天 {int(hours)} 时 {int(minutes)} 分 {int(seconds)} 秒')
        print('*'*100)

(4) Write test.py

from logistics_info import LogisticsInfo
from logistics_info_analysis import LogisticsInfoAnalysis

if __name__ == '__main__':

    num = '7835562143****'  # 快递单号
    com = 'zhongtong'    # 快递公司

    info = LogisticsInfo(num, com).logistics()  # 物流信息
    # print(test)
    LogisticsInfoAnalysis(info).logistics_info_analysis()   # 分析并输出物流信息

 Precautions:

The courier company code can be downloaded from the official website of Express 100:

4. Test

(1) run test.py

(2) View wuliu.json

The data obtained by calling the API is also saved in data/wuliu.json:

Guess you like

Origin blog.csdn.net/spx_0108/article/details/131869711