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

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

前言
在日常开发和学习中,我们经常需要获取天气数据来开发各种应用或进行分析。本文将介绍如何使用Python编写一个简单的天气数据爬虫,从公开的天气网站抓取所需信息。

准备工作
在开始之前,我们需要安装一些必要的Python库:

pip install requests beautifulsoup4 pandas

requests:用于发送HTTP请求

beautifulsoup4:用于解析HTML内容

pandas:用于数据处理和存储

选择目标网站
我们需要选择一个提供天气数据的网站。本文以中国天气网(http://www.weather.com.cn)为例。在实际操作中,请确保遵守网站的robots.txt协议和使用条款。

爬取单个城市天气数据

  1. 分析网页结构
    首先,我们打开中国天气网,搜索一个城市(如北京),观察URL结构:
    http://www.weather.com.cn/weather/101010100.shtml

其中101010100是北京的城市代码。我们可以通过查找其他城市的代码来获取不同城市的天气。

  1. 编写爬虫代码
import requests
from bs4 import BeautifulSoup
import pandas as pd

def get_weather(city_code):
    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/58.0.3029.110 Safari/537.3'
    }
    
    try:
        response = requests.get(url, headers=headers)
        response.encoding = 'utf-8'
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 获取城市名称
        city = soup.find('div', class_='crumbs fl').find_all('a')[-1].text
        
        # 获取7天天气数据
        weather_data = []
        items = soup.find_all('li', class_='sky')
        
        for item in items:
            date = item.find('h1').text
            weather = item.find('p', class_='wea').text
            temp = item.find('p', class_='tem').text.strip()
            wind = item.find('p', class_='win').find('i').text
            
            weather_data.append({
                '城市': city,
                '日期': date,
                '天气': weather,
                '温度': temp,
                '风向': wind
            })
            
        return weather_data
    
    except Exception as e:
        print(f"获取天气数据失败: {e}")
        return None

# 北京的城市代码
beijing_weather = get_weather('101010100')

if beijing_weather:
    df = pd.DataFrame(beijing_weather)
    print(df)
    # 保存为CSV文件
    df.to_csv('beijing_weather.csv', index=False, encoding='utf-8-sig')
  1. 代码解析
    我们定义了一个get_weather函数,接收城市代码作为参数

使用requests发送GET请求获取网页内容

使用BeautifulSoup解析HTML,提取所需数据

将提取的数据组织成字典列表

最后使用pandas将数据转换为DataFrame并保存为CSV文件

爬取多个城市天气数据
要获取多个城市的天气,我们需要知道各个城市的代码。这里我们预先准备一个城市代码字典:

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

def get_multiple_cities_weather(city_dict):
    all_weather_data = []
    
    for city_name, city_code in city_dict.items():
        print(f"正在获取{city_name}的天气数据...")
        weather_data = get_weather(city_code)
        if weather_data:
            all_weather_data.extend(weather_data)
        # 避免请求过于频繁,添加延迟
        time.sleep(2)
    
    if all_weather_data:
        df = pd.DataFrame(all_weather_data)
        df.to_csv('multi_cities_weather.csv', index=False, encoding='utf-8-sig')
        print("数据已保存为multi_cities_weather.csv")
        return df
    else:
        return None

# 使用示例
import time
weather_df = get_multiple_cities_weather(city_codes)
if weather_df is not None:
    print(weather_df.head())

数据可视化(可选)
我们可以使用matplotlib对获取的天气数据进行简单的可视化:

import matplotlib.pyplot as plt

# 假设我们已经有了包含多个城市天气数据的DataFrame
# 首先转换温度数据(原始数据可能是"12℃/-3℃"这样的格式)
def extract_max_temp(temp_str):
    try:
        return int(temp_str.split('/')[0].replace('℃', ''))
    except:
        return None

df['最高温度'] = df['温度'].apply(extract_max_temp)

# 绘制各城市最高温度对比
plt.figure(figsize=(10, 6))
for city in df['城市'].unique():
    city_data = df[df['城市'] == city]
    plt.plot(city_data['日期'], city_data['最高温度'], label=city)

plt.xlabel('日期')
plt.ylabel('最高温度(℃)')
plt.title('各城市最高温度对比')
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

完整代码
以下是完整的代码示例:

import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
import matplotlib.pyplot as plt

def get_weather(city_code):
    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/58.0.3029.110 Safari/537.3'
    }
    
    try:
        response = requests.get(url, headers=headers)
        response.encoding = 'utf-8'
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 获取城市名称
        city = soup.find('div', class_='crumbs fl').find_all('a')[-1].text
        
        # 获取7天天气数据
        weather_data = []
        items = soup.find_all('li', class_='sky')
        
        for item in items:
            date = item.find('h1').text
            weather = item.find('p', class_='wea').text
            temp = item.find('p', class_='tem').text.strip()
            wind = item.find('p', class_='win').find('i').text
            
            weather_data.append({
                '城市': city,
                '日期': date,
                '天气': weather,
                '温度': temp,
                '风向': wind
            })
            
        return weather_data
    
    except Exception as e:
        print(f"获取天气数据失败: {e}")
        return None

def get_multiple_cities_weather(city_dict):
    all_weather_data = []
    
    for city_name, city_code in city_dict.items():
        print(f"正在获取{city_name}的天气数据...")
        weather_data = get_weather(city_code)
        if weather_data:
            all_weather_data.extend(weather_data)
        # 避免请求过于频繁,添加延迟
        time.sleep(2)
    
    if all_weather_data:
        df = pd.DataFrame(all_weather_data)
        df.to_csv('multi_cities_weather.csv', index=False, encoding='utf-8-sig')
        print("数据已保存为multi_cities_weather.csv")
        return df
    else:
        return None

def visualize_temperature(df):
    # 转换温度数据
    def extract_max_temp(temp_str):
        try:
            return int(temp_str.split('/')[0].replace('℃', ''))
        except:
            return None
    
    df['最高温度'] = df['温度'].apply(extract_max_temp)
    
    # 绘制图表
    plt.figure(figsize=(10, 6))
    for city in df['城市'].unique():
        city_data = df[df['城市'] == city]
        plt.plot(city_data['日期'], city_data['最高温度'], 'o-', label=city)
    
    plt.xlabel('日期')
    plt.ylabel('最高温度(℃)')
    plt.title('各城市最高温度对比')
    plt.legend()
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.show()

if __name__ == '__main__':
    city_codes = {
        '北京': '101010100',
        '上海': '101020100',
        '广州': '101280101',
        '深圳': '101280601',
        '杭州': '101210101'
    }
    
    weather_df = get_multiple_cities_weather(city_codes)
    
    if weather_df is not None:
        print(weather_df.head())
        visualize_temperature(weather_df)

结语
本文介绍了如何使用Python爬取天气数据的基本方法。通过这个例子,你可以学习到:

使用requests库发送HTTP请求

使用BeautifulSoup解析HTML内容

数据的提取、组织和存储

简单的数据可视化

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

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

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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值