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

相关推荐
Greyson12 分钟前
如何通过Vagrant快速建库_自动化虚拟机Oracle部署方案
jvm·数据库·python
西西弗Sisyphus4 分钟前
Python 闭包实现的计数器,每调用一次就 +1,多个计数器之间互不干扰
python·闭包·closure
Wyz201210246 分钟前
HTML函数运行时触控屏失灵是硬件故障吗_输入层兼容性测试【详解】
jvm·数据库·python
jiguanghover11 分钟前
python 更新Obsidian
python
Greyson114 分钟前
TensorFlow中如何冻结模型层_设置layer.trainable等于False实现微调
jvm·数据库·python
m0_7488394914 分钟前
SQL视图在ETL流程中的作用_数据清洗与标准化接口
jvm·数据库·python
2401_8326355816 分钟前
JavaScript中字符串toLowerCase与toUpperCase规范
jvm·数据库·python
龙腾AI白云16 分钟前
大模型微调进阶:多任务微调实战
python·机器学习·逻辑回归·pygame
gihigo199817 分钟前
分布式发电的配电网有功-无功综合优化 MATLAB 实现
开发语言·分布式·matlab
人工干智能17 分钟前
科普:python的pandas包中的DataFrame就是二维表
开发语言·python·pandas