1、任務(wù)描述
1.1、需求分析
-
在2345天氣信息網(wǎng)2345天氣網(wǎng)依據(jù)地點(diǎn)和時(shí)間對(duì)相關(guān)城市的歷史天氣信息進(jìn)行爬取。
1.2 頁面分析
-
網(wǎng)頁使用get方式發(fā)送請(qǐng)求,所需參數(shù)包括areaInfo[areaId]、areaInfo[areaType]、date[year]、date[month],分別為城市id、城市類型,年、月。
2、獲取網(wǎng)頁源碼、解析、保存數(shù)據(jù)
import pandas as pd
import requests
from bs4 import BeautifulSoup
url = "https://tianqi.2345.com/Pc/GetHistory"
def crawl_html(year, month):
"""依據(jù)年月爬取對(duì)應(yīng)的數(shù)據(jù)"""
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年北京歷史天氣數(shù)據(jù)
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、結(jié)果展示
文章來源地址http://www.zghlxwxcb.cn/news/detail-732400.html
文章來源:http://www.zghlxwxcb.cn/news/detail-732400.html
到了這里,關(guān)于【python爬蟲】——?dú)v史天氣信息爬取的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!