从api网址提取信息

假王

我正在尝试从一堆不同的邮政编码中提取该API的平均温度。目前,我可以通过手动更改API网址中的邮政编码来实现,但是我希望它能够遍历邮政编码列表或请求输入并使用这些邮政编码。但是,我还很新,对如何向链接中添加变量和填充物一无所知,或者使它过于复杂。因此,基本上,我正在寻找一些方法来将变量添加到链接中,或者添加具有相同效果的东西,以便可以随时更改它。

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"])

西亚兰·奥布赖恩(Ciaran O Brien)
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来实现所需的功能。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章