帮我写一个用python爬取上海过去5年的天气数据并保存到tianqi.csv文件中的代码
时间: 2024-06-10 16:09:17 浏览: 132
好的,以下是代码:
```python
import requests
import csv
url = 'http://www.tianqihoubao.com/lishi/shanghai/month/{}.html'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
years = ['2016', '2017', '2018', '2019', '2020']
months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
data = []
for year in years:
for month in months:
html = requests.get(url.format(year+month), headers=headers).text
trs = html.split('<tr>')[1:-1]
for tr in trs:
tds = tr.split('</td>')
date = tds[0][4:] + '-' + month
high_temp = tds[1][4:]
low_temp = tds[2][4:]
weather = tds[3][4:]
wind_direction = tds[4][4:]
wind_speed = tds[5][4:]
data.append([date, high_temp, low_temp, weather, wind_direction, wind_speed])
with open('tianqi.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['日期', '最高温度', '最低温度', '天气', '风向', '风速'])
writer.writerows(data)
print('数据已保存到tianqi.csv文件中')
```
请问还有什么其它问题需要我回答吗?
阅读全文