python爬取天气信息

该博客展示了如何使用Python爬虫从weather.com.cn获取惠州的天气信息,并进行数据清洗,将结果写入txt文件。主要涉及urllib和re模块,通过正则表达式提取数据,最后将天气信息按指定格式存储。

python爬取天气信息

python爬取天气信息
1.导入python及其他模块

import re
import urllib
import urllib.request
import pprint
import os as myos
import datetime

2主程序

num =3
isend=[ ]
if __name__ == '__main__':
    print(datetime.datetime.now())
    url = r"http://www.weather.com.cn/weather/101280301.shtml" #进行多网页下载
    print(url)
    html = load_page(url,1)
    # pprint.pprint(html)
    get_image(html,num )
    print(datetime.datetime.now())

3申请网站天气信息

def load_page(url,myflag):
    request = urllib.request.Request(url)
    response = urllib.request.urlopen(request)
    if myflag==1:
        data=response.read().decode()
    if myflag==2:
         data = response.read()
    return data

4.清洗数据

def get_image(html,num):
    location=[]
    location_1=[]
    location_2=[]
    regx = r'hour3data=[\S]*'
    pattern = re.compile(regx)
    get_image = re.findall(pattern, repr(html))
    print(type(get_image))

    for item in get_image:
        print(type(item))
    print(item)
    s=item.replace('"','[')
    t=s.split('[')

    for i1 in t:
        regx = r'\d+日.*'
        pattern = re.compile(regx)
        t1=re.findall(pattern, repr(i1))
        if t1!=[]:
            location.append(t1[0]) 
    #数据中有重复内容通过比对截取 
    myint1=0
    for item2 in location:
        if item2==location[0]:
            location_1.append(myint1)
        myint1+=1
    pprint.pprint(location_1) 
    #location_1中只有一个元素,无重复数据。
    if len(location_1)==1:
        location_2=location
    #location_1中大于一个元素,有重复数据
    if len(location_1)>1:
        location_2=location[location_1[1]:]

    pprint.pprint(location_2)  
    print(len(location_2))
    
    for item in location_2:
        myweite=datetime.datetime.now().__str__()+ "----惠州天气---"+item[0:len(item)-1]+"\n"
        with open('D:\\图片\\惠州天气.txt', 'a')as fb:
            fb.write(myweite)    

5运行效果图:在这里插入图片描述

在这里插入图片描述

<think>好的,我需要帮用户提供一个Python爬取天气信息的代码示例。用户之前已经问过相关的问题,我的回答里包含了使用requests和BeautifulSoup的示例,现在用户再次请求代码示例,可能需要更详细的说明或者不同的数据源。 首先,查看用户提供的引用内容,引用1到5提到了不同的方法,包括爬取中国天气网、保存为CSV、可视化分析等。用户现在明确需要代码示例,可能希望更具体的实现,比如完整的爬取流程或者如何处理数据。 考虑到用户之前的问题中,我给出了一个简单的例子,但用户可能需要更完整的代码,包含错误处理、数据存储等。另外,引用2和4提到将数据保存为CSV,并进行可视化,所以用户可能希望代码包含这些部分。 需要确保代码符合用户的需求,比如爬取中国天气网的数据,使用requests和BeautifulSoup,然后存储到CSV。同时,用户可能需要知道如何解析不同的数据,比如温度、湿度等。 另外,用户可能关心反爬机制,比如设置User-Agent,处理可能的异常,比如网络请求失败或元素未找到的情况。在之前的回答中,我提到了需要添加健壮性和异常处理,所以应该在代码中体现这一点。 还要注意引用中的内容,比如引用3和4提到使用pandas处理数据,matplotlib和pyecharts进行可视化。用户可能需要代码示例中包含这些步骤,但当前问题主要询问爬取代码,所以可能先提供爬取和存储的部分,再简要提及可视化。 需要检查中国天气网的结构是否有变化,之前的示例代码可能基于旧的HTML结构,需要确保选择正确的CSS选择器或类名。可能需要查看中国天气网的页面结构,确保示例代码的有效性。 最后,用户可能需要知道如何运行代码,比如安装必要的库(requests, BeautifulSoup, pandas),所以应该在代码前注明安装命令。同时,需要处理可能出现的编码问题,比如网页编码为UTF-8或GBK,确保正确解析。 总结步骤:导入库、发送请求、解析HTML、提取数据、存储到CSV、异常处理、可视化示例。确保代码结构清晰,注释详细,方便用户理解和修改。</think>### Python爬取天气信息代码示例(基于中国天气网) #### 一、核心步骤与完整代码 ```python import requests from bs4 import BeautifulSoup import pandas as pd from datetime import datetime def fetch_weather(city_code="101010100"): # 北京城市代码 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/119.0.0.0 Safari/537.36', 'Referer': 'http://www.weather.com.cn/' } try: response = requests.get(url, headers=headers, timeout=10) response.encoding = 'utf-8' # 显式指定编码 soup = BeautifulSoup(response.text, 'lxml') # 定位天气数据容器 weather_box = soup.find('ul', class_='t clearfix') if not weather_box: raise ValueError("天气数据容器未找到") # 解析当天数据 today_data = weather_box.find('li', class_='on') date = today_data.find('h1').get_text().strip() weather = today_data.find('p', class_='wea').get_text().strip() temp = today_data.find('p', class_='tem').get_text().replace('\n', '') wind = today_data.find('p', class_='win').find('i').get_text().strip() # 存储数据 data = { '城市': get_city_name(city_code), '日期': f"{datetime.now().year}-{date}", '天气': weather, '温度': temp, '风力': wind } return data except Exception as e: print(f"抓取失败: {str(e)}") return None def get_city_name(code): # 城市代码映射表(部分示例) city_map = { "101010100": "北京", "101020100": "上海", "101280101": "广州" } return city_map.get(code, "未知城市") def save_to_csv(data, filename='weather.csv'): df = pd.DataFrame([data]) df.to_csv(filename, mode='a', header=not pd.io.common.file_exists(filename), index=False) if __name__ == "__main__": result = fetch_weather("101020100") # 上海 if result: save_to_csv(result) print(f"数据已保存:\n{result}") ``` #### 二、关键功能说明 1. **城市代码机制** 中国天气网使用特定城市编码(如北京101010100),可通过[国家气象信息中心](http://www.nmc.cn/)查询完整编码表[^2] 2. **反爬策略处理** - 添加`User-Agent`模拟浏览器 - 设置`Referer`头降低封禁风险 - 使用`timeout`防止请求阻塞 3. **数据持久化** 采用追加模式写入CSV文件,支持多批次数据采集[^4] #### 三、进阶可视化示例 ```python # 可视化分析(需先积累数据) import matplotlib.pyplot as plt def plot_temperature(): df = pd.read_csv('weather.csv') df['日期'] = pd.to_datetime(df['日期']) plt.figure(figsize=(12,6)) df['温度'].str.extract('(-?\d+)/(-?\d+)℃').astype(float).mean(axis=1).plot() plt.title('温度变化趋势') plt.xlabel('日期') plt.ylabel('平均温度(℃)') plt.grid(True) plt.show() # plot_temperature() # 取消注释运行 ``` #### 四、运行准备 ```bash # 安装依赖库 pip install requests beautifulsoup4 pandas matplotlib ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

a7660331a

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值