python用和风天气API获取辽宁省各个市的近几天的天气并导出到excel
时间: 2024-06-09 13:06:48 浏览: 140
好的,使用和风天气API需要先进行注册并获取API Key,接着使用requests库发送请求并获取天气数据,最后使用pandas库将数据导出到excel中。
以下是示例代码:
```python
import requests
import pandas as pd
# 和风天气API Key
key = "your_api_key"
# 获取天气数据
def get_weather(city):
url = f"https://devapi.qweather.com/v7/weather/3d?location={city}&key={key}"
response = requests.get(url)
weather_data = response.json()["daily"]
return weather_data
# 获取辽宁省各个市的天气数据
cities = ["沈阳", "大连", "鞍山", "抚顺", "本溪", "丹东", "锦州", "营口", "阜新", "辽阳", "盘锦", "铁岭", "朝阳", "葫芦岛"]
weather_data = {}
for city in cities:
weather_data[city] = get_weather(city)
# 将数据导出到excel文件
with pd.ExcelWriter("Liaoning_weather.xlsx") as writer:
for city, data in weather_data.items():
df = pd.DataFrame(data)
df.to_excel(writer, sheet_name=city)
```
其中,通过和风天气API获取的天气数据中包括了每个城市未来三天的天气情况,包括日期、白天和晚上的天气情况、温度范围、降水概率等信息,可以根据实际需求选择导出哪些数据。
阅读全文