爬取长春冬季的历史天气数据 python
时间: 2023-10-02 14:07:27 浏览: 236
你可以使用 Python 中的 requests 和 BeautifulSoup 库来爬取长春市历史天气数据。以下是基本的爬虫代码:
```python
import requests
from bs4 import BeautifulSoup
# 设置请求头,模拟浏览器请求
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'}
# 构造请求 URL,以2020年为例
url = 'https://lishi.tianqi.com/changchun/202001.html'
# 发送 GET 请求,获取 HTML 页面
response = requests.get(url, headers=headers)
# 解析 HTML 页面
soup = BeautifulSoup(response.content, 'html.parser')
# 找到天气数据所在的表格
table = soup.find('div', class_='tqtongji2')
# 找到每一行数据
rows = table.find_all('tr')
# 遍历每一行数据,提取出需要的数据
for row in rows:
data = row.find_all('td')
date = data[0].text.strip()
high_temp = data[1].text.strip()
low_temp = data[2].text.strip()
weather = data[3].text.strip()
wind_direction = data[4].text.strip()
wind_power = data[5].text.strip()
# 输出数据
print(date, high_temp, low_temp, weather, wind_direction, wind_power)
```
上述代码中,我们使用 requests 库发送 GET 请求获取 HTML 页面,并使用 BeautifulSoup 库解析页面。然后,我们找到天气数据所在的表格,并遍历每一行数据,提取出日期、最高温度、最低温度、天气状况、风向和风力数据。最后,我们输出提取出的数据。
你可以根据上述代码自行修改 URL 中的年份和月份,以获取不同时间段内的天气数据。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)