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

相关推荐
开发者小天1 分钟前
python中的class类
开发语言·python
idwangzhen11 分钟前
GEO优化系统哪家更专业
python·信息可视化
2501_9333295514 分钟前
Infoseek数字公关AI中台技术解析:如何构建企业级舆情监测与智能处置系统
开发语言·人工智能
m0_7066532314 分钟前
基于C++的爬虫框架
开发语言·c++·算法
梵刹古音15 分钟前
【C语言】 数据类型的分类
c语言·开发语言
diediedei21 分钟前
嵌入式数据库C++集成
开发语言·c++·算法
xie0510_24 分钟前
string模拟实现
开发语言·c++·算法
diediedei28 分钟前
机器学习模型部署:将模型转化为Web API
jvm·数据库·python
FAFU_kyp29 分钟前
RISC0_ZERO项目在macOs上生成链上证明避坑
开发语言·后端·学习·macos·rust
m0_5613596730 分钟前
使用Python自动收发邮件
jvm·数据库·python