【python爬虫】——历史天气信息爬取

文章目录

1、任务描述

1.1、需求分析

  • 在2345天气信息网2345天气网依据地点时间 对相关城市的历史天气信息进行爬取。

1.2 页面分析

  • 网页使用get方式发送请求,所需参数包括areaInfo[areaId]、areaInfo[areaType]、date[year]、date[month],分别为城市id、城市类型,年、月。

2、获取网页源码、解析、保存数据

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

url = "https://tianqi.2345.com/Pc/GetHistory"
def crawl_html(year, month):
    """依据年月爬取对应的数据"""
    params = {'areaInfo[areaId]': 54511,
            'areaInfo[areaType]': 2,
            'date[year]': year,
            'date[month]': month}

    headers = {'User-Agent':'''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36'''}

    response = requests.get(url, headers=headers, params=params)
    data = response.json()["data"]
    
    df = pd.read_html(data)[0]
    return df

# 下载2015-2023年北京历史天气数据
df_list = []
for year in range(2015, 2023):
    for month in range(1, 13):
        print("爬取:%d年 %d月"%(year, month))
        df = crawl_html(year, month)
        df_list.append(df)

pd.concat(df_list).to_excel("practice04_BeijingWeather.xlsx", index=False)

3、结果展示

相关推荐
再见晴天*_*14 小时前
SpringBoot 中单独一个类中运行main方法报错:找不到或无法加载主类
java·开发语言·intellij idea
lqjun082716 小时前
Qt程序单独运行报错问题
开发语言·qt
酷飞飞17 小时前
Python网络与多任务编程:TCP/UDP实战指南
网络·python·tcp/ip
hdsoft_huge18 小时前
Java & Spring Boot常见异常全解析:原因、危害、处理与防范
java·开发语言·spring boot
风中的微尘18 小时前
39.网络流入门
开发语言·网络·c++·算法
数字化顾问18 小时前
Python:OpenCV 教程——从传统视觉到深度学习:YOLOv8 与 OpenCV DNN 模块协同实现工业缺陷检测
python
未来之窗软件服务19 小时前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
小冯记录编程19 小时前
C++指针陷阱:高效背后的致命危险
开发语言·c++·visual studio
学生信的大叔19 小时前
【Python自动化】Ubuntu24.04配置Selenium并测试
python·selenium·自动化
1uther19 小时前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎