从天气网爬取某城市往年的天气数据并保存到CSV文件
时间: 2024-06-08 07:06:12 浏览: 16
这里提供一个Python的示例代码,使用BeautifulSoup和requests库从天气网爬取北京市2019年1月份的天气数据,并将数据保存到CSV文件中。
```python
import requests
from bs4 import BeautifulSoup
import csv
# 设置请求头,模拟浏览器访问
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.36 Edge/16.16299',
}
# 发送请求,获取页面内容
url = 'http://www.tianqihoubao.com/lishi/beijing/month/201901.html'
response = requests.get(url, headers=headers)
html = response.content
# 解析页面内容,获取所需数据
soup = BeautifulSoup(html, 'html.parser')
table = soup.find_all('table', class_='b')
rows = table[0].find_all('tr')
data = []
for row in rows[1:]:
cols = row.find_all('td')
cols = [col.text.strip() for col in cols]
data.append(cols)
# 将数据保存到CSV文件中
with open('beijing_weather_201901.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['日期', '天气状况', '气温', '风力风向'])
writer.writerows(data)
```
这里使用requests库发送请求,BeautifulSoup库解析HTML页面内容,然后将所需数据保存到CSV文件中。你可以根据需要修改代码中的请求链接、文件名和保存数据的列名。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)