【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、结果展示

相关推荐
Python私教4 分钟前
Playwright MCP 用 a11y 树抓页面:比全量 DOM 省 token 的采集 Agent
爬虫
郭涤生9 分钟前
不同主机之间网络通信-以太网连接复习
开发语言·rk3588
山居秋暝LS13 分钟前
【无标题】RTX00安装paddle OCR,win11不能装最新的,也不能用GPU
开发语言·r语言
卢锡荣18 分钟前
单芯通吃,盲插标杆 —— 乐得瑞 LDR6020,Type‑C 全场景互联 “智慧芯”
c语言·开发语言·计算机外设
Xin_ye1008622 分钟前
C# 零基础到精通教程 - 第七章:面向对象编程(入门)——类与对象
开发语言·c#
彦为君38 分钟前
Agent 安全:从权限提示到沙箱隔离
python·ai·ai编程
AI科技星1 小时前
《数学公理体系·第三部·数术几何》(2026 年版)
c语言·开发语言·线性代数·算法·矩阵·量子计算·agi
审判长烧鸡1 小时前
【Go工具】go-playground是什么组织?官方的?
开发语言·安全·go
PILIPALAPENG1 小时前
Python 语法速成指南:前端开发者视角(JS 类比版)
前端·人工智能·python
kkeeper~1 小时前
0基础C语言积跬步之字符函数与字符串函数(上)
c语言·开发语言