从 api url 中提取信息 [英] Pulling info from an api url
问题描述
我试图从这个 API 中从一堆不同的邮政编码中提取温度的平均值.我目前可以通过手动更改 API 的 URL 中的邮政编码来实现,但我希望它能够遍历邮政编码列表或要求输入并使用这些邮政编码.但是,我是新手,不知道如何将变量和内容添加到链接中,要么是这样,要么是我过于复杂了.所以基本上我正在寻找一些方法来向链接添加变量或具有相同效果的东西,以便我可以随时更改它.
I'm trying to pull the average of temperatures from this API from a bunch of different ZIP codes. I can currently do so by manually changing the ZIP code in the URL for the API, but I was hoping it to be able to loop through a list of ZIP codes or ask for input and use those zip codes. However, I'm rather new and have no idea on how to add variables and stuff to a link, either that or I'm overcomplicating it. So basically I was searching for some methods to add a variable to the link or something to the same effect so I can change it whenever I want.
import urllib.request
import json
out = open("output.txt", "w")
link = "http://api.openweathermap.org/data/2.5/weather?zip={zip-code},us&appid={api-key}"
print(link)
x = urllib.request.urlopen(link)
url = x.read()
out.write(str(url, 'utf-8'))
returnJson = json.loads(url)
print('\n')
print(returnJson["main"]["temp"])
推荐答案
import urllib.request
import json
zipCodes = ['123','231','121']
out = open("output.txt", "w")
for i in zipCodes:
link = "http://api.openweathermap.org/data/2.5/weather?zip=" + i + ",us&appid={api-key}"
x = urllib.request.urlopen(link)
url = x.read()
out.write(str(url, 'utf-8'))
returnJson = json.loads(url)
print(returnJson["main"]["temp"])
out.close()
您可以通过遍历邮政编码列表并从中创建新 URL 来实现您想要的.
You can achieve what you want by looping through a list of zipcodes and creating a new URL from them.
这篇关于从 api url 中提取信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!