繁体   English   中英

如何在Python中使用API​​从CSV文件读取数据

[英]How to read data from a csv file using API in Python

我正在尝试从以下链接下载数据:
NHTSA网站

如果我按以下方式创建链接,则它将CSV文件下载到我的计算机上http://webapi.nhtsa.gov/api/SafetyRatings/modelyear/2019/make/ACURA/model/RDX?format=csv

如何使用Python中的API读取不同车辆的此文件?

到目前为止,这是我的代码:

db = sql.connect("localhost","root","password","TEST")

cursor = db.cursor()

sql = "SELECT * FROM TEST.car_model"
cursor.execute(sql)

data = cursor.fetchall()

for row in data:
    apiUrl = "http://webapi.nhtsa.gov/api/SafetyRatings/modelyear/"
    apiParams = str(row[1])+"/make/"+row[2].replace(" ","%20")+"/model/"+row[3].rstrip().replace(" ","%20")
    apiFormat = "?format=csv"
    link = apiUrl + apiParams + apiFormat
    response = urlopen(apiUrl + apiParams + apiFormat)

    f = open(link, 'rb')
    reader = csv.reader(f)
    for row in reader:
        print(row)

db.close()

响应会自动将文件下载到我的“下载”文件夹中吗?

你可以试试这个

model = input("Enter model name: ")
year = input("year: ")

url = "http://webapi.nhtsa.gov/api/SafetyRatings/modelyear/"+year+"/make/ACURA/model/"+model+"?format=csv"

import urllib.request

with urllib.request.urlopen(url) as response:
    html = response.read()

with open(model+year+".csv", "w") as f:
    f.write(html)


您可以在网址中添加更多变量。 然后,您可以使用pandas软件包进行阅读。

import pandas as pd
vechiles = pd.read_csv("vichles.csv")

暂无
暂无

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

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