python爬虫爬取年际气温数据
时间: 2024-12-26 07:13:40 浏览: 5
### 使用 Python 编写爬虫程序抓取年度气温数据
为了实现这一目标,可以采用 `requests` 和 `BeautifulSoup` 库来处理网页请求与解析 HTML 文档。对于结构化较好的页面,如表格形式展示的数据,还可以考虑使用 Pandas 的 `read_html()` 方法简化操作过程[^3]。
#### 准备工作
安装必要的第三方库:
```bash
pip install requests beautifulsoup4 pandas lxml openpyxl
```
#### 获取并分析目标网页内容
通过发送 HTTP 请求访问指定 URL 地址获取所需年份的温度资料:
```python
import requests
from bs4 import BeautifulSoup as BSoup
import pandas as pd
def fetch_temperature_data(year):
url = f"https://www.example.com/weather/{year}" # 替换为目标站点的实际链接
response = requests.get(url)
if not response.ok:
raise Exception(f"Failed to load page {url}")
soup = BSoup(response.text, 'lxml')
table = soup.find('table', {'class': 'weather-data'}) # 查找特定样式类别的表格元素
df_list = pd.read_html(str(table))
temperature_df = df_list[0]
return temperature_df
```
此函数接收一个参数 year 表示想要查询的具体年份,并返回包含当月平均最高温最低温和降水量等信息的数据框对象。
#### 数据清洗与保存至 Excel 文件
对原始数据进行初步清理去除不必要的列或行之后再导出到本地磁盘上便于后续可视化或其他用途:
```python
def clean_and_save(df, filename="temperature.xlsx"):
cleaned_df = (
df.dropna(how='all') # 删除完全为空白的所有行
.drop(columns=['Unnamed:*']) # 移除未命名字段
[['Date', 'Max Temp (°C)', ...]] # 只保留日期以及感兴趣的几项指标
)
writer = pd.ExcelWriter(filename, engine='openpyxl')
cleaned_df.to_excel(writer, index=False)
writer.save()
```
最后调用上述定义好的两个辅助方法完成整个流程即可获得一份完整的年度气象统计报表。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.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)