使用python爬虫北京2022年的天气信息,输出月份,温度,空气质量,相对湿度
时间: 2024-06-08 17:09:14 浏览: 117
好的,我们可以使用Python中的requests和BeautifulSoup库来爬取北京2022年每个月的天气信息。以下是代码示例:
```python
import requests
from bs4 import BeautifulSoup
# 循环遍历每个月份
for month in range(1, 13):
# 构建url
url = f'http://www.tianqihoubao.com/lishi/beijing/2022{month:02d}.html'
# 发送请求
response = requests.get(url)
# 解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 获取表格中的所有行
rows = soup.find('table', {'class': 'b'}).findAll('tr')
# 遍历每一行,跳过表头
for row in rows[1:]:
# 获取每一列
cols = row.findAll('td')
# 提取需要的信息
date = cols[0].text.strip()
temperature = cols[1].text.strip()
air_quality = cols[2].text.strip()
humidity = cols[6].text.strip()
# 输出信息
print(f'{month}月 {date} 温度:{temperature} 空气质量:{air_quality} 相对湿度:{humidity}')
```
运行以上代码,即可输出每个月份的天气信息。注意,该网站只提供2022年1月到12月的天气信息。