从 api url 中提取信息
Pulling info from an api url
我正试图从这个 API 的一堆不同的邮政编码中提取平均温度。我目前可以通过手动更改 URL 中的邮政编码来实现 API,但我希望它能够循环遍历邮政编码列表或要求输入并使用这些 zip代码。
但是,我是个新手,不知道如何将变量和内容添加到 link,或者我把它弄得太复杂了。所以基本上我是在寻找一些方法来将变量添加到 link 或具有相同效果的东西,这样我就可以随时更改它。
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 来实现您想要的。
我正试图从这个 API 的一堆不同的邮政编码中提取平均温度。我目前可以通过手动更改 URL 中的邮政编码来实现 API,但我希望它能够循环遍历邮政编码列表或要求输入并使用这些 zip代码。 但是,我是个新手,不知道如何将变量和内容添加到 link,或者我把它弄得太复杂了。所以基本上我是在寻找一些方法来将变量添加到 link 或具有相同效果的东西,这样我就可以随时更改它。
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 来实现您想要的。