最近天氣降溫厲害,咱們用Python
來(lái)分析一下空氣質(zhì)量如何~
話不多說(shuō),我們直接開(kāi)始上手。
環(huán)境以及模塊
環(huán)境使用
- Python 3.8
- Pycharm
- nodejs
模塊使用
- import requests
- import execjs
- import json
requests
和execjs
都是第三方模塊,需要手動(dòng)安裝,直接pip install 加上模塊名字即可。
思路流程
一. 數(shù)據(jù)來(lái)源分析
-
明確需求:
明確采集的網(wǎng)站以及數(shù)據(jù)
- 網(wǎng)站: 目標(biāo)網(wǎng)址
- 數(shù)據(jù):
空氣質(zhì)量相關(guān)數(shù)據(jù)
-
抓包分析:
通過(guò)瀏覽器自帶的開(kāi)發(fā)者工具分析數(shù)據(jù)
- 打開(kāi)開(kāi)發(fā)者工具: F12
- 刷新網(wǎng)頁(yè)
- 通過(guò)關(guān)鍵字搜索查詢對(duì)應(yīng)數(shù)據(jù)包位置
二. 代碼實(shí)現(xiàn)步驟
- 發(fā)送請(qǐng)求 -> 模擬瀏覽器對(duì)于url地址發(fā)送請(qǐng)求
- 獲取數(shù)據(jù) -> 獲取服務(wù)器返回響應(yīng)數(shù)據(jù)
- 解析數(shù)據(jù) -> 提取具體數(shù)據(jù)內(nèi)容
- 保存數(shù)據(jù) -> 保存表格文件中
代碼展示
定義月份列表,用于循環(huán)請(qǐng)求數(shù)據(jù)。
month_list = ['202301', '202302', '202303', '202304','202305','202306','202308','202309','202310']
?
循環(huán)請(qǐng)求每個(gè)月份的數(shù)據(jù)
for month in month_list:
?
發(fā)送請(qǐng)求
headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36' } # 請(qǐng)求鏈接 # 完整的源碼和視頻講解我都打包好 # 在這個(gè)摳裙自取 708525271 url = 'https://www.aqistudy.cn/historydata/api/historyapi.php'
?
調(diào)用JS代碼獲取加密參數(shù)
# 讀取js文件 data_file = open('data.js', 'r', encoding='utf-8').read() # 編譯JS代碼 data_code = execjs.compile(data_file) # 參數(shù) m0fhOhhGL = "GETDAYDATA" oNLhNQ = { "city": "北京", "month": month } # 調(diào)用js代碼函數(shù) hA4Nse2cT = data_code.call('post_data', m0fhOhhGL, oNLhNQ) print('加密的請(qǐng)求參數(shù): ', hA4Nse2cT) # 請(qǐng)求參數(shù) data = { 'hA4Nse2cT': hA4Nse2cT } # 發(fā)送請(qǐng)求 response = requests.post(url=url, data=data, headers=headers).text
?
解密響應(yīng)加密數(shù)據(jù)
# 讀取文件 response_file = open('response.js', 'r', encoding='utf-8').read() # 編譯文件 response_code = execjs.compile(response_file) # 調(diào)用js函數(shù) result = response_code.call('dxvERkeEvHbS', response) print('加密的響應(yīng)數(shù)據(jù): ',response) print('明文響應(yīng)數(shù)據(jù): ',result)
?
保存數(shù)據(jù)
將解密后的數(shù)據(jù)保存到Excel文件中
json_data = json.loads(result) content_list = [] for index in json_data['result']['data']['items']: content_list.append(index) df_data = pd.DataFrame(content_list) df_data.to_excel(f'{month}.xlsx', index=False)
?
?
效果展示
?
?
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-746411.html
好了今天的內(nèi)容就分享到這,下次見(jiàn)~文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-746411.html
到了這里,關(guān)于簡(jiǎn)單的用Python實(shí)現(xiàn)一下JS逆向解密,采集空氣質(zhì)量數(shù)據(jù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!