Skip to content
On this page

如何调用天气API获取天气信息

安装依赖、代码、运行结果

利用weatherapi生成密钥,链接得到api

https://api.openweathermap.org/data/2.5/weather?q=Beijing&appid=my_apikey

在vscode里编写代码得到信息

python
import requests

url = "https://api.openweathermap.org/data/2.5/weather?q=Beijing&appid=my_apikey"
response = requests.get(url)
data = response.json()
if data.get("cod") != 200:
    print("城市不存在或API出错")
else:   
    print("城市:", data["name"])
    print("温度:", data["main"]["temp"] - 273.15)
    print("天气描述:", data["weather"][0]["description"])