python查询中国天气的代码
时间: 2023-02-19 07:08:45 浏览: 57
这是一段使用 Python 查询中国天气的代码示例:
```
import requests
def get_weather(city):
# 先定义一个函数, 用于查询天气
api_url = "http://api.openweathermap.org/data/2.5/weather"
# 定义 API 的地址
params = {
"q": city,
"appid": "your-api-key", # 替换为你的 API Key
"units": "metric",
}
# 定义请求参数
response = requests.get(api_url, params=params)
# 发送请求
data = response.json()
# 解析响应
weather = data["weather"][0]["description"]
# 获取天气信息
temperature = data["main"]["temp"]
# 获取温度信息
return f"{city}的天气是{weather}, 温度是{temperature}摄氏度"
city = input("请输入你要查询的城市名称: ")
# 读取用户输入的城市名称
print(get_weather(city))
# 调用函数并打印结果
```
这段代码使用了 Python 的 `requests` 库来发送 HTTP 请求, 并使用了 OpenWeatherMap 的 API 来获取天气信息。需要注意的是, 需要在代码中替换为你自己的 API Key。
你可以在 OpenWeatherMap 的网站上注册一个免费账号, 并在网站上申请一个 API Key。然后, 就可以使用这段代码查询中国的天气了。
希望这对你有帮助!