Python爬取天气数据实战教程:从入门到精通

包含编程籽料、学习路线图、爬虫代码、安装包等!【点击领取】

前言
在数据获取与分析的时代,网络爬虫技术成为了数据采集的重要手段。本文将介绍如何使用Python爬取天气数据,并存储为结构化格式,适合数据分析、可视化等后续处理。本教程适合Python初学者和有一定基础的开发者。

一、准备工作
1.1 所需工具
Python 3.x

requests库(发送HTTP请求)

BeautifulSoup4或lxml(HTML解析)

pandas(数据处理)

开发环境(推荐PyCharm、VS Code或Jupyter Notebook)

1.2 安装依赖库

pip install requests beautifulsoup4 pandas lxml

二、选择目标网站
本教程以中国天气网(http://www.weather.com.cn)为例,爬取城市天气预报数据。

注意:在实际爬取前,请务必:

查看目标网站的robots.txt文件

遵守网站的使用条款

设置合理的爬取间隔,避免对服务器造成过大压力

三、基础爬取实现
3.1 获取网页内容

import requests
from bs4 import BeautifulSoup

# 定义目标URL(以北京为例)
url = "http://www.weather.com.cn/weather/101010100.shtml"

# 设置请求头,模拟浏览器访问
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'
}

# 发送HTTP请求
response = requests.get(url, headers=headers)
response.encoding = 'utf-8'  # 设置编码

# 检查请求是否成功
if response.status_code == 200:
    html = response.text
else:
    print(f"请求失败,状态码:{response.status_code}")

3.2 解析天气数据

# 使用BeautifulSoup解析HTML
soup = BeautifulSoup(html, 'lxml')

# 查找天气数据所在的标签
weather_data = []
days = soup.select('.t > li')

for day in days:
    # 提取日期
    date = day.select_one('.date').get_text(strip=True)
    
    # 提取天气状况
    weather = day.select_one('.wea').get_text(strip=True)
    
    # 提取温度
    temp = day.select_one('.tem').get_text(strip=True).replace('\n', '')
    
    # 提取风向风力
    wind = day.select_one('.win > em > span')['title']
    wind_force = day.select_one('.win > i').get_text(strip=True)
    
    weather_data.append({
        '日期': date,
        '天气': weather,
        '温度': temp,
        '风向': wind,
        '风力': wind_force
    })

print(weather_data)

四、数据存储与处理
4.1 使用pandas处理数据

import pandas as pd

# 将数据转换为DataFrame
df = pd.DataFrame(weather_data)

# 数据清洗
df['最高温度'] = df['温度'].str.extract(r'/(\d+)℃')
df['最低温度'] = df['温度'].str.extract(r'(\d+)℃/')

# 删除原始温度列
df.drop('温度', axis=1, inplace=True)

print(df.head())

4.2 存储为CSV文件

# 保存为CSV文件
df.to_csv('weather_data.csv', index=False, encoding='utf-8-sig')

print("天气数据已保存为weather_data.csv")

4.3 存储到数据库(可选)
如果需要存储到MySQL数据库:

import pymysql
from sqlalchemy import create_engine

# 创建数据库连接
engine = create_engine('mysql+pymysql://username:password@localhost:3306/weather_db')

# 存储到数据库
df.to_sql('weather', con=engine, if_exists='replace', index=False)

print("天气数据已存储到数据库")

五、进阶技巧
5.1 多城市天气爬取

city_codes = {
    '北京': '101010100',
    '上海': '101020100',
    '广州': '101280101',
    '深圳': '101280601'
}

all_weather_data = []

for city, code in city_codes.items():
    url = f"http://www.weather.com.cn/weather/{code}.shtml"
    response = requests.get(url, headers=headers)
    response.encoding = 'utf-8'
    
    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'lxml')
        days = soup.select('.t > li')
        
        for day in days:
            date = day.select_one('.date').get_text(strip=True)
            weather = day.select_one('.wea').get_text(strip=True)
            temp = day.select_one('.tem').get_text(strip=True).replace('\n', '')
            wind = day.select_one('.win > em > span')['title']
            wind_force = day.select_one('.win > i').get_text(strip=True)
            
            all_weather_data.append({
                '城市': city,
                '日期': date,
                '天气': weather,
                '温度': temp,
                '风向': wind,
                '风力': wind_force
            })
    else:
        print(f"{city}天气数据获取失败")

# 转换为DataFrame并保存
multi_city_df = pd.DataFrame(all_weather_data)
multi_city_df.to_csv('multi_city_weather.csv', index=False, encoding='utf-8-sig')

5.2 使用API获取天气数据(推荐)
许多天气服务提供商提供API接口,比网页爬取更稳定可靠。例如:

import requests

# 使用和风天气API示例(需要申请API key)
api_key = "your_api_key"
location = "101010100"  # 北京的城市代码
url = f"https://devapi.qweather.com/v7/weather/7d?location={location}&key={api_key}"

response = requests.get(url)
if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print("API请求失败")

六、反爬虫策略应对
6.1 常见反爬措施
User-Agent检测:我们已经设置了User-Agent

请求频率限制:添加延时

IP封锁:使用代理IP

验证码:需要更复杂的处理

6.2 添加随机延时

import time
import random

# 在请求之间添加随机延时
time.sleep(random.uniform(1, 3))  # 1-3秒随机延时

6.3 使用代理IP

proxies = {
    'http': 'http://your_proxy_ip:port',
    'https': 'https://your_proxy_ip:port'
}

response = requests.get(url, headers=headers, proxies=proxies)

七、完整代码示例

import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
import random

def get_weather_data(city_code, city_name):
    url = f"http://www.weather.com.cn/weather/{city_code}.shtml"
    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'
    }
    
    try:
        response = requests.get(url, headers=headers)
        response.encoding = 'utf-8'
        
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'lxml')
            days = soup.select('.t > li')
            weather_data = []
            
            for day in days:
                date = day.select_one('.date').get_text(strip=True)
                weather = day.select_one('.wea').get_text(strip=True)
                temp = day.select_one('.tem').get_text(strip=True).replace('\n', '')
                wind = day.select_one('.win > em > span')['title']
                wind_force = day.select_one('.win > i').get_text(strip=True)
                
                weather_data.append({
                    '城市': city_name,
                    '日期': date,
                    '天气': weather,
                    '温度': temp,
                    '风向': wind,
                    '风力': wind_force
                })
            
            return weather_data
        else:
            print(f"{city_name}天气数据获取失败,状态码:{response.status_code}")
            return None
    except Exception as e:
        print(f"获取{city_name}天气数据时出错:{str(e)}")
        return None

def main():
    city_codes = {
        '北京': '101010100',
        '上海': '101020100',
        '广州': '101280101',
        '深圳': '101280601'
    }
    
    all_weather_data = []
    
    for city, code in city_codes.items():
        print(f"正在获取{city}的天气数据...")
        weather_data = get_weather_data(code, city)
        if weather_data:
            all_weather_data.extend(weather_data)
        time.sleep(random.uniform(1, 3))  # 随机延时
    
    if all_weather_data:
        df = pd.DataFrame(all_weather_data)
        # 数据清洗
        df['最高温度'] = df['温度'].str.extract(r'/(\d+)℃')
        df['最低温度'] = df['温度'].str.extract(r'(\d+)℃/')
        df.drop('温度', axis=1, inplace=True)
        
        # 保存数据
        df.to_csv('multi_city_weather.csv', index=False, encoding='utf-8-sig')
        print("天气数据已保存为multi_city_weather.csv")
    else:
        print("未能获取任何天气数据")

if __name__ == "__main__":
    main()

八、总结
本文介绍了使用Python爬取天气数据的基本流程,包括:

发送HTTP请求获取网页内容

使用BeautifulSoup解析HTML

提取并清洗所需数据

存储为CSV或数据库

应对反爬虫策略

希望本教程能帮助你掌握Python爬取天气数据的基本技能,为进一步的数据分析项目打下基础。

最后:
希望你编程学习上不急不躁,按照计划有条不紊推进,把任何一件事做到极致,都是不容易的,加油,努力!相信自己!

文末福利
最后这里免费分享给大家一份Python全套学习资料,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。

包含编程资料、学习路线图、源代码、软件安装包等!【点击这里】领取!
① Python所有方向的学习路线图,清楚各个方向要学什么东西
② 100多节Python课程视频,涵盖必备基础、爬虫和数据分析
③ 100多个Python实战案例,学习不再是只会理论
④ 华为出品独家Python漫画教程,手机也能学习

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值