Python爬取天气网站数据的实战教程

引言

在日常生活中,天气信息对我们至关重要。本文将通过实战方式,详细讲解如何使用Python爬取某天气网站的数据,并展示如何整理和存储这些数据。我们将使用requests库来获取网页数据,使用BeautifulSoup库来解析网页,并使用pandas库来存储数据。【完整代码在文末】

准备工作

安装必要的库:

python 复制代码
pip install requests  
pip install beautifulsoup4  
pip install pandas

了解目标网页结构:

在编写爬虫之前,需要先分析目标网页的结构,可以使用浏览器的开发者工具来查看网页元素。

编写爬虫代码

导入库:

python 复制代码
import requests  
from bs4 import BeautifulSoup  
import pandas as pd

定义获取网页内容的函数:

python 复制代码
def get_html(url):  
    try:  
        headers = {  
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'  
        }  
        r = requests.get(url, headers=headers)  
        r.raise_for_status()  
        r.encoding = r.apparent_encoding  
        return r.text  
    except Exception as e:  
        print(e)  
        return ""

解析网页内容:

python 复制代码
def parse(html):  
    soup = BeautifulSoup(html, "html.parser")  
    weather_list = soup.find('div', class_='weather-list')  
    items = weather_list.find_all('div', class_='weather-item')  
    data = []  
    for item in items:  
        city = item.find('h2').get_text()  
        temp = item.find('p', class_='temp').get_text()  
        weather = item.find('p', class_='weather').get_text()  
        data.append({'City': city, 'Temperature': temp, 'Weather': weather})  
    return data

保存数据到CSV文件:

php 复制代码
```python
def save_to_csv(data):  
    df = pd.DataFrame(data)  
    df.to_csv('weather_data.csv', index=False, encoding='utf-8-sig')
主函数:
python
def main():  
    url = "http://example.com/weather"  # 假设这是目标天气网站的URL  
    html = get_html(url)  
    data = parse(html)  
    save_to_csv(data)  
    print("数据爬取完成,并已保存到CSV文件。")  
 
if __name__ == "__main__":  
    main()

运行和测试

运行上述代码,如果一切正常,你将看到控制台输出"数据爬取完成,并已保存到CSV文件。",并且在你的代码目录下生成了一个名为weather_data.csv的文件,里面包含了爬取到的天气数据。

注意事项

遵守爬虫道德与法律: 爬取网站数据时,请确保遵守网站的robots.txt文件,不要对网站服务器造成过大压力。 反爬虫机制:

有些网站会有反爬虫机制,如IP封禁、动态加载数据等。遇到这类问题,可能需要使用更高级的爬虫技术,如Selenium。 数据准确性:

爬取的数据可能存在误差或更新不及时的情况,使用时请注意数据的准确性和时效性。

通过上述步骤,你可以实现一个简单的天气网站数据爬虫。希望这篇文章能为你提供一些帮助!

扫描下方二维码,免费获取本文章源码、 Python公开课和大佬打包整理的几百G的学习资料,内容包含但不限于Python电子书、教程、项目接单等等:

相关推荐
曲幽6 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805111 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon12 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly12 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程13 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly14 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风21 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风21 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风2 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python