SoFunction
Updated on 2025-03-01

Use Python to extract express information

1. Preface

Before extracting express information, we need to understand the basic principles of express query. Most express delivery companies provide express query API interfaces. By calling these interfaces, we can obtain real-time information about express delivery. This article will introduce how to use Python to call the express query API interface and extract the express information we need.

2. Preparation

Before you start, you need to make sure that you have the Python environment installed and be familiar with the basics of Python programming. In addition, you need to find a reliable express query API interface and obtain the corresponding API key.

3. Install the necessary libraries

In order to call the API interface and parse the returned JSON data, we need to install the requests library. You can use pip to install:

pip install requests

4. Write code

Import the necessary libraries

import requests  
import json

Define express query function

def query_express(express_code, api_key):  
    """
     Query express information
     :param express_code: express order number
     :param api_key: API key
     :return: express information
     """  
    # Express query API interface address    url = "/express/query"  
      
    # Build request parameters    params = {  
        "code": express_code,  
        "key": api_key  
    }  
      
    # Send a request    response = (url, params=params)  
      
    # parse the returned JSON data    data = ()  
      
    # Extract express delivery information    express_info = {  
        "Express Order Number": data["result"]["logisticCode"],  
        "Express Company": data["result"]["companyName"],  
        "Logistics Status": data["result"]["status"],  
        "Latest update time": data["result"]["lastUpdateTime"],  
        "Logistics Details": data["result"]["data"]  
    }  
      
    return express_info

In the above code, we define a query_express function to query express information. The function accepts two parameters: express_code represents the express order number, and api_key represents the API key. The function first builds the request parameters, and then sends a GET request to the express query API interface. Next, the function parses the returned JSON data, extracts the express information we need, and finally returns a dictionary containing the express information.

Call express query function

Now, we can call the query_express function to query the express information. Suppose we have a express order number 1234567890 and an API key your_api_key, we can call the function like this:

express_code = "1234567890"  
api_key = "your_api_key"  
express_info = query_express(express_code, api_key)  
print(express_info)

After running the above code, you will see an output similar to the following:

{  
'Express Order Number': '1234567890',
'Express Company': 'ZTO Express',
'Logistics Status': 'Signed',
'Latest update time': '2023-04-20 15:30:00',
'Logistics Details': [
{'time': '2023-04-20 15:30:00', 'context': 'Signed, signing person: myself'},
{'time': '2023-04-20 14:00:00', 'context': 'Dispatch, sender: Zhang San'},
# ... Other logistics details ...
    ]  
}

5. Advanced operation

On the basis of extracting express delivery information, we can also perform some advanced operations to meet more complex needs.

Check express delivery information regularly

If you need to query the information of a certain express order number regularly, you can use Python's schedule library to implement timing tasks. By setting the query time interval, you can regularly get the latest status of the express delivery.

Install the schedule library:

pip install schedule

Use schedule to query express delivery information regularly:

import schedule  
import time  
  
def query_and_print_express(express_code, api_key):  
    express_info = query_express(express_code, api_key)  
    print(express_info)  
  
def main():  
    express_code = "1234567890"  
    api_key = "your_api_key"  
      
    # Query express information once an hour    (1).(query_and_print_express, express_code, api_key)  
      
    while True:  
        schedule.run_pending()  
        (1)  
  
if __name__ == "__main__":  
    main()

In the above code, we use (1).() to set the query_and_print_express function to be executed once an hour. We then use an infinite loop to run the timing task until the program is manually stopped.

Send express delivery information notification

In addition to printing express information to the console, you can also send express information to your mobile phone or email address to keep up to date with the latest status of express delivery. You can use Python's smtplib and email library to send email notifications, or use third-party services such as WeChat notifications.

Sample code for sending email notifications:

import smtplib  
from  import MIMEText  
from  import MIMEMultipart  
  
def send_email(subject, content, to_email):  
    # Email Server Settings    smtp_server = ''  
    smtp_port = 587  
    sender_email = 'your_email@'  
    password = 'your_email_password'  
      
    # Create a mail object    msg = MIMEMultipart()  
    msg['From'] = sender_email  
    msg['To'] = to_email  
    msg['Subject'] = subject  
    (MIMEText(content, 'plain'))  
      
    # Send email    with (smtp_server, smtp_port) as server:  
        ()  
        (sender_email, password)  
        (sender_email, to_email, msg.as_string())  
  
#User Examplesubject = "Express information update"  
content = "Your express delivery has arrived, please pick up the order as soon as possible."  
to_email = "your_recipient_email@"  
send_email(subject, content, to_email)

In the above code, we use the smtplib library to connect to the mailbox server and use MIMEText and MIMEMultipart to build the mail content. Then, we call the() method to send the email. You need to replace smtp_server, smtp_port, sender_email, and password with your own mailbox server settings.

6. Things to note

When using Python to extract express information, you need to pay attention to the following points:

  • API Key Protection: Make sure your API key is kept properly and do not hardcode it in code or share it publicly. It is best to store the API key in an environment variable or configuration file and load dynamically at runtime.
  • Error handling: When writing code, consider various possible exceptions and add corresponding error handling logic. For example, when the API interface returns an error code or cannot connect, a friendly prompt message should be given.
  • Comply with the usage agreement: When using the express query API interface, the provider's usage agreement and restrictions must be complied with. Do not frequently request or abuse the API interface to avoid being blocked or incur additional costs.
  • Data security: When processing express delivery information, pay attention to protecting user privacy and data security. Do not disclose user express information to unauthorized third parties.

Through the introduction of this article, I believe you have mastered the basic methods of using Python to extract express information. You can expand and optimize according to your needs to achieve more efficient express information query function. I wish you better results in practice!

This is the end of this article about using Python to extract express information. For more related content of Python to extract express information, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!