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

相关推荐
数据知道几秒前
PostgreSQL 实战:详解 UPSERT(INSERT ON CONFLICT)
数据库·python·postgresql
June bug几秒前
(#数组/链表操作)寻找两个正序数组的中位数
数据结构·python·算法·leetcode·面试·职场和发展·跳槽
李昊哲小课24 分钟前
奶茶店销售额预测模型
python·机器学习·线性回归·scikit-learn
电商API&Tina25 分钟前
电商API接口的应用与简要分析||taobao|jd|微店
大数据·python·数据分析·json
郝学胜-神的一滴30 分钟前
深入理解Linux套接字(Socket)编程:从原理到实践
linux·服务器·开发语言·网络·c++·程序人生·算法
向前V34 分钟前
Flutter for OpenHarmony轻量级开源记事本App实战:笔记编辑器
开发语言·笔记·python·flutter·游戏·开源·编辑器
时艰.39 分钟前
JVM — Java 类加载机制
java·开发语言·jvm
嫂子的姐夫43 分钟前
25-jsl:gov公安(全扣补环境版)
爬虫·逆向·加速乐
小小码农Come on1 小时前
QT中窗口位置、相对位置、绝对位置
android·开发语言·qt
snow_star_dream1 小时前
(笔记)VSC python应用--函数补全注释添加
笔记·python