python循环来提取API数据以用于迭代URL



我正试图建立一个for循环,以获取大约600000个邮政编码的民选代表数据。基本URL保持不变,唯一更改的部分是邮政编码。

理想情况下,我想创建一个所有邮政编码的列表,然后使用requests.get来获取列表中所有邮政代码的数据。我在下面想出了这个代码,但它只是提取我列表中最后一个邮政编码的数据。我真的不知道为什么会发生这种情况,而且我是一个蟒蛇初学者,所以任何帮助都将不胜感激!


#loop test 
postcodes = ['P0L1B0','P5A3P1', 'P5A3P2', 'P5A3P3']
for i in range(len(postcodes)):
rr = requests.get('https://represent.opennorth.ca/postcodes/{}'.format(postcodes[i]))
data1=json.loads(rr.text)
data1

您的代码无法工作,因为它覆盖了data1。

试试这个:

#loop test 
responses = list() # stores responses for postal codes
postcodes = ['P0L1B0','P5A3P1', 'P5A3P2', 'P5A3P3']
for postcode in postcodes:
rr = requests.get('https://represent.opennorth.ca/postcodes/{}'.format(postcode))
data=json.loads(rr.text)
responses.append(data)

您的回复现在保存在回复列表中。

提示:
您可以在不使用索引的情况下对列表进行迭代。

每次迭代都要覆盖data1变量,这就是为什么最终只使用最后一个变量的原因,您需要以不同的方式存储它。

示例:

postcodes =['P0L1B0','P5A3P1', 'P5A3P2', 'P5A3P3']
results = []
for postcode in postcodes:
res = requests.get('https://represent.opennorth.ca/postcodes/{}'.format(postcode))
if res.status_code == 200:
results.append(res.json())
else: 
print("Request to {} failed".format(postcode))

您正在查看最后一个响应。

#loop test 
postcodes = ['P0L1B0','P5A3P1', 'P5A3P2', 'P5A3P3']
api_data = dict()
for i in postcodes:
rr = requests.get('https://represent.opennorth.ca/postcodes/{}'.format(i))
data = json.loads(rr.text)
api_data.update({i: data})   
# or print(data)
print(api_data)

在这里,我添加了dict的所有响应,key作为邮政编码,value作为响应。

最新更新