简体   繁体   English

如何使用 Python 中的请求库获取多个参数?

[英]How to use requests library in Python for multiple parameters?

I'm working on a program in Python that takes a vehicle registration and returns its MOT history by using MOT Trade API.我正在 Python 中开发一个程序,该程序使用 MOT Trade API 进行车辆登记并返回其 MOT 历史记录。 So far, I've got the program working for one vehicle.到目前为止,我已经让该程序适用于一辆车。 I would like the program to look-up multiple vehicles by importing an excel file that contains a list of vehicle registrations.我希望程序通过导入包含车辆登记列表的 excel 文件来查找多辆车辆。 Here is my code:这是我的代码:

import requests
from datetime import datetime
import smtplib
import time
import pandas as pd

df = pd.read_excel(r'vehicles.xlsx')  # Reading the excel file with the vehicle database
reg = df['registration']

headers = {
        'Accept': 'application/json',
        'x-api-key': apiKey,
    }

    params = (
        ('registration', reg),
    )
    response = requests.get('https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests',
                            headers=headers, params=params)

def check_days_left():
    r = response.json()  # This returns a list of dicts of the full MOT History data
    carDetails = r[0]  # Access the first dictionary of the list which is MOT tests
    motTests = carDetails['motTests']  # This returns a list of dicts of the MOT tests
    latestTest = motTests[0]  # Access the first dictionary to get the details of the latest test
    expDate = latestTest['expiryDate']  # This returns the expiry date key of the latest test dictionary
    uk_date = datetime.strptime(expDate, '%Y.%m.%d')  # Convert expDate to datetime format
    difference = uk_date - datetime.now()  # Gets the timedelta between now and expiry date
    days_left = difference.days  # Extract the number of days from the above as an int
    print(days_left)

check_days_left()

At the moment, this returns the MOT details for the last vehicle in the excel file, ignoring the rest.目前,这将返回 excel 文件中最后一辆车的 MOT 详细信息,忽略 rest。 Any help is much appreciated.任何帮助深表感谢。 Thanks!谢谢!

You can loop through all the registration number and request to the api to get result of each registration number.您可以遍历所有注册号并向 api 请求以获取每个注册号的结果。

A working solution might look like following code -一个可行的解决方案可能类似于以下代码 -

import requests
from datetime import datetime
import smtplib
import time
import pandas as pd

df = pd.read_excel(r'vehicles.xlsx')  # Reading the excel file with the vehicle database
registrations = df['registration'].tolist()

r = []

# loop through all the registration number in registrations array.
for reg in registrations:
    headers = {
        'Accept': 'application/json',
        'x-api-key': apiKey,
    }
    params = {
        'registration': reg,
    }
    # Add the response from the api in the array `r`
    r.append(requests.get('https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests', headers=headers, params=params).json())


def check_days_left():
    r = response.json()  # This returns a list of dicts of the full MOT History data
    carDetails = r[0]  # Access the first dictionary of the list which is MOT tests
    motTests = carDetails['motTests']  # This returns a list of dicts of the MOT tests
    latestTest = motTests[0]  # Access the first dictionary to get the details of the latest test
    expDate = latestTest['expiryDate']  # This returns the expiry date key of the latest test dictionary
    uk_date = datetime.strptime(expDate, '%Y.%m.%d')  # Convert expDate to datetime format
    difference = uk_date - datetime.now()  # Gets the timedelta between now and expiry date
    days_left = difference.days  # Extract the number of days from the above as an int
    print(days_left)

check_days_left()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM