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

相关推荐
basketball6165 分钟前
C++ 构造函数完全指南:从入门到进阶
java·开发语言·c++
互联科技报9 分钟前
2026超融合选型:Top5品牌与市场格局解读
开发语言·perl
weixin1997010801629 分钟前
[特殊字符] 智能数据采集:数字化转型的“数据石油勘探队”(附Python实战源码)
开发语言·python
想唱rap1 小时前
IO多路转接之poll
服务器·开发语言·数据库·c++
@杰克成1 小时前
Java学习30
java·开发语言·学习
次元工程师!1 小时前
LangFlow开发(三)—Bundles组件架构设计(3W+字详细讲解)
java·前端·python·低代码·langflow
三品吉他手会点灯1 小时前
C语言学习笔记 - 40.数据类型 - scanf函数的编程规范与非法输入处理
c语言·开发语言·笔记·学习
凯瑟琳.奥古斯特1 小时前
数据冗余与规范化的本质[数据库原理]
开发语言·数据库·职场和发展
t_hj2 小时前
大模型微调
人工智能·python·深度学习
码农老李2 小时前
openEuler2403服务器版 原生官方镜像和飞腾定制镜像
开发语言·php