python用和风天气API获取辽宁省各个市的近几天的天气并导出到excel
时间: 2024-06-09 09:06:49 浏览: 56
好的,首先你需要申请和风天气的API Key,然后安装requests和openpyxl库。以下是示例代码:
```python
import requests
import openpyxl
# 设置API Key和请求参数
api_key = "你的API Key"
province = "辽宁省"
cities = ["沈阳市", "大连市", "鞍山市"]
days = 3
url = f"https://devapi.heweather.net/v7/weather/3d?parameters&key={api_key}&location="
# 发送请求获取数据
results = []
for city in cities:
res = requests.get(url + province + city).json()
results.append(res["daily"])
# 写入Excel文件
wb = openpyxl.Workbook()
for i, city in enumerate(cities):
ws = wb.create_sheet(city)
ws.append(["日期", "白天天气", "夜间天气", "最高温度", "最低温度"])
for j in range(days):
date = results[i][j]["fxDate"]
daytime_weather = results[i][j]["textDay"]
nighttime_weather = results[i][j]["textNight"]
max_temp = results[i][j]["tempMax"]
min_temp = results[i][j]["tempMin"]
ws.append([date, daytime_weather, nighttime_weather, max_temp, min_temp])
wb.save("天气预报.xlsx")
print("数据已写入Excel文件")
```
注意,以上示例代码只是一种实现方式,具体实现还需要根据自己的需求进行修改。
阅读全文