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

相关推荐
小鸡吃米…5 小时前
TensorFlow 实现梯度下降优化
人工智能·python·tensorflow·neo4j
tod1135 小时前
C++ 核心知识点全解析(七)
开发语言·c++·面试经验
njsgcs5 小时前
py不等于python
开发语言·python
沐知全栈开发5 小时前
Vue3 事件处理
开发语言
轩情吖5 小时前
Qt的事件
开发语言·qt·事件·qt事件·qkeyevent·qmoveevent
敲敲了个代码5 小时前
构建工具的第三次革命:从 Rollup 到 Rust Bundler,我是如何设计 robuild 的
开发语言·前端·javascript·后端·rust
张铁铁是个小胖子5 小时前
mysql事务的隔离性如何保证
java·开发语言
天空属于哈夫克35 小时前
Java 开发|企微外部群主动发送小程序消息实战
开发语言·python·小程序·自动化·企业微信·rpa
戴西软件5 小时前
PreSys在爆炸与多介质流固耦合中的建模方法:从ALE到SPH的工程实践
linux·python·程序人生·cae
xyq20245 小时前
C语言中的递归
开发语言