如何使用Python中的API从csv文件读取数据

2024-05-01 22:02:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如果我创建如下链接,它会在我的机器上下载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()

response会自动将文件下载到我的下载文件夹中吗?在


Tags: 文件csvhttpdbsqlmodel链接cursor
1条回答
网友
1楼 · 发布于 2024-05-01 22:02:17

你可以试试这个

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)


您可以向url添加更多变量。你可以用熊猫软件包阅读。

^{pr2}$

相关问题 更多 >