python如何爬取中央气象台历史天气数据
时间: 2024-06-01 22:04:18 浏览: 215
以下是使用Python爬取中央气象台历史天气数据的方法示例:
1. 导入所需的库:
```python
import requests
from bs4 import BeautifulSoup
```
2. 构造请求URL:
```python
year = 2021
month = 1
url = f"http://www.weather.com.cn/weather/{year}{month}/"
```
3. 发送请求并获取页面内容:
```python
response = requests.get(url)
html = response.text
```
4. 解析页面内容:
```python
soup = BeautifulSoup(html, "html.parser")
```
5. 提取所需的数据:
```python
weather_data = []
table = soup.find("table", class_="forecast-table")
rows = table.find_all("tr")
for row in rows:
cols = row.find_all("td")
if len(cols) == 5:
date = cols[0].text.strip()
weather = cols[1].text.strip()
temperature = cols[2].text.strip()
wind = cols[3].text.strip()
weather_data.append((date, weather, temperature, wind))
```
6. 打印结果:
```python
for data in weather_data:
print(data)
```
阅读全文