【问题标题】:Pulling info from an api url从 api url 中提取信息
【发布时间】:2021-05-16 16:31:28
【问题描述】:

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

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

【问题讨论】:

    标签: python json urllib


    【解决方案1】:
    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 来实现您想要的。

    【讨论】:

    • 所以我真的只是想多了。感谢您的帮助。
    • 对代码进行了编辑以匹配您最初的内容。我希望这行得通。如果是这样,请务必将其标记为正确。 @FalseKing
    猜你喜欢
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2015-05-25
    • 1970-01-01
    相关资源
    最近更新 更多