我們?cè)趯懪老x的過(guò)程中,除了研究反爬之外,幾乎全部的時(shí)間都在寫解析邏輯。那么,生命苦短,為什么我們不寫一個(gè)通用解析器呢?對(duì)啊!為什么不呢?開整!
爬蟲要解析的網(wǎng)頁(yè)類型無(wú)外乎 html、json 以及一些二進(jìn)制文件(video、excel 文件等)。既然要做成通用解析器,我們有兩種實(shí)現(xiàn)方式,一種是將網(wǎng)頁(yè)內(nèi)容轉(zhuǎn)換成統(tǒng)一的形式,然后用對(duì)應(yīng)的解析規(guī)則去解析,比如全部將網(wǎng)頁(yè)內(nèi)容轉(zhuǎn)換成 html 形式,然后用 xpath 去提取。
另外一種是配置文件預(yù)先告知的方式,你配置成什么類型,解析器就通過(guò)對(duì)應(yīng)的解析規(guī)則去解析。
統(tǒng)一網(wǎng)頁(yè)形式,需要做大量的網(wǎng)頁(yè)內(nèi)容形式轉(zhuǎn)換,而配置文件預(yù)先告知?jiǎng)t需要在配置時(shí)指定更多解析字段。相比較而言,通過(guò)第二種方式,未來(lái)改變較多的是配置規(guī)則,不需要?jiǎng)雍诵拇a,引入 bug 的可能性較低。因此這里我們采用第二種方式實(shí)現(xiàn)解析器
解析器對(duì)于網(wǎng)頁(yè)內(nèi)容的提取,本質(zhì)上和我們?cè)诒镜仉娔X上查找和整理文件,沒有什么差別。比如像下面這樣
解析內(nèi)容就是從中提取我們想要的信息,然后整理成我們希望的格式。比如上面的內(nèi)容,我們提取出來(lái)的形式應(yīng)該是這樣
{ "design": "設(shè)計(jì)圖.psd", "software": "sketch.dmg" }
而在實(shí)際的爬蟲開發(fā)過(guò)程中,網(wǎng)頁(yè)形式遠(yuǎn)比以上的復(fù)雜。其實(shí)遇到最多的問題是在一組列表中嵌套一個(gè)列表,我們需要把這種形式提取出來(lái)。比如像下面這種形式
{ "a": "a", "b": [ {"c": "c1", "d": "d1"}, {"c": "c2", "d": "d2"}] }
他提取出信息后應(yīng)該是這樣
[ { "a": "a", "c": "c1", "d": "d1" }, { "a": "a", "c": "c2", "d": "d2" } ]
如果小伙伴對(duì)于算法熟悉的話,應(yīng)該能察覺出這種遍歷用遞歸來(lái)寫是非常方便的。但要注意的是 python 會(huì)限定遞歸的層數(shù),小伙伴可以通過(guò)下面這個(gè)方法查看遞歸限定的層數(shù)
import sys print(sys.getrecursionlimit()) >>>1000
我這邊限定的層數(shù)是 1k。對(duì)于解析網(wǎng)頁(yè)來(lái)說(shuō)完全夠用了,如果哪個(gè)人把網(wǎng)頁(yè)解析邏輯嵌套了 1000 層,我建議你直接跟老板提放棄這個(gè)網(wǎng)頁(yè)吧!
我們已經(jīng)知道對(duì)于通用解析來(lái)說(shuō),就是通過(guò)配置解析規(guī)則提取頁(yè)面的對(duì)應(yīng)信息。而針對(duì)有列表層級(jí)的網(wǎng)頁(yè)可能還涉及遞歸遍歷問題。那如何去配置這種解析規(guī)則呢?其實(shí)很簡(jiǎn)單,只需要在進(jìn)入每一個(gè)層級(jí)之前先指定該層的數(shù)據(jù)形式,比如下面這個(gè)原數(shù)據(jù)
{ "a": "a", "b": [ {"c": "c1", "d": "d1"}, {"c": "c2", "d" : "d2"} ] }
想提取嵌套信息,我們的解析規(guī)則就應(yīng)該是這樣的
[ { "$name": "a", "$value_type": "raw", "$parse_method": "json", "$parse_rule": "a", "$each": [] }, { "$name": "__datas__", "$value_type": "recursion", "$parse_method": "json", "$parse_rule": "b", "$each": [ { "$name": "c", "$value_type": "raw", "$parse_method": "json", "$parse_rule": "c", "$each": [] }, { "$name": "d", "$value_type": "raw", "$parse_method": "json", "$parse_rule": "d", "$each": [] } ] } ]
其中 $name 字段表示我們最終希望最外層數(shù)據(jù)所擁有的字段名,當(dāng)然如果是需要遞歸到內(nèi)層的字段,則將列表保存為 __datas__ ,然后根據(jù)這個(gè) __datas__ 進(jìn)行內(nèi)層結(jié)構(gòu)的解析。最終我們得到的數(shù)據(jù)結(jié)構(gòu)應(yīng)該是這樣的
[ {"a": "a", "c": "c1", "d": "d1"}, {"a": "a", "c": "c2", "d": "d2"} ]
以上我們只演示了 json 的解析規(guī)則,如果要拿來(lái)解析 html 對(duì)象呢?很簡(jiǎn)單,將解析方式改為 xpath 對(duì)象,然后傳入 xpath 解析語(yǔ)法即可。
總共分成兩部分,一部分根據(jù)原最終結(jié)果和規(guī)則進(jìn)行打包,將所有涉及 recursion 邏輯的字段進(jìn)行轉(zhuǎn)換,代碼如下
def _pack_json(result, rules): item = {} for p_rule in rules: if p_rule.get("$value_type") == "raw": if p_rule.get("$parse_method") == "json": item[p_rule.get("$name")] = glom(result, p_rule.get("$parse_rule")) elif p_rule.get("$value_type") == "recursion": if p_rule.get("$parse_method") == "json": tmp_result = glom(result, p_rule.get("$parse_rule")) total_result = [] for per_r in tmp_result: total_result.append(_pack_json(per_r, p_rule.get("$each"))) item[p_rule.get("$name")] = total_result return item
另外一部分將上一步得到的進(jìn)行解析,將打包得到的結(jié)果進(jìn)行解包,即將所有內(nèi)嵌的數(shù)據(jù)提到最外層,代碼如下
def _unpack_datas(result: dict) -> list: if "__datas__" not in result: return [result] item_results = [] all_item = result.pop("__datas__") for per_item in all_item: if "__datas__" in per_item: tmp_datas = per_item.pop("__datas__") for per_tmp_data in tmp_datas: tmp_item = _unpack_datas(per_tmp_data) for per_tmp_item in tmp_item: item_results.append({**per_tmp_item, **per_item}) else: item_results.append({**result, **per_item}) return item_results
后再包一層執(zhí)行入口就可以了,完整代碼如下
from loguru import logger from glom import glom def parse(result, rules): def _pack_json(result, rules): item = {} for p_rule in rules: if p_rule.get("$value_type") == "raw": if p_rule.get("$parse_method") == "json": item[p_rule.get("$name")] = glom(result, p_rule.get("$parse_rule")) elif p_rule.get("$value_type") == "recursion": if p_rule.get("$parse_method") == "json": tmp_result = glom(result, p_rule.get("$parse_rule")) total_result = [] for per_r in tmp_result: total_result.append(_pack_json(per_r, p_rule.get("$each"))) item[p_rule.get("$name")] = total_result return item def _unpack_datas(result: dict) -> list: if "__datas__" not in result: return [result] item_results = [] all_item = result.pop("__datas__") for per_item in all_item: if "__datas__" in per_item: tmp_datas = per_item.pop("__datas__") for per_tmp_data in tmp_datas: tmp_item = _unpack_datas(per_tmp_data) for per_tmp_item in tmp_item: item_results.append({**per_tmp_item, **per_item}) else: item_results.append({**result, **per_item}) return item_results pack_result = _pack_json(result, rules) logger.info(pack_result) return _unpack_datas(pack_result)
以上,就是通用解析器的完整案例。案例中僅實(shí)現(xiàn)了對(duì)于 json 的支持,小伙伴可以基于自己的項(xiàng)目,改造成其他的解析形式。通用解析其實(shí)是雞仔為了偷懶寫的,因?yàn)殡u仔發(fā)現(xiàn),在爬蟲開發(fā)中,大部分工作都耗在解析這部分。而有了通用解析的前端頁(yè)面,運(yùn)營(yíng)和數(shù)據(jù)分析師就可以根據(jù)自己的需要配置自己想爬取的站點(diǎn)了。人生苦短,你懂得。我去摸魚了~
實(shí)現(xiàn)方式請(qǐng)移步至 github 查看:https://github.com/hacksman/learn_lab/blob/master/small_bug_lab/general_parser.py
以上就是python 用遞歸實(shí)現(xiàn)通用爬蟲解析器的詳細(xì)內(nèi)容,更多關(guān)于python 遞歸實(shí)現(xiàn)爬蟲解析器的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
標(biāo)簽:呼和浩特 衡水 江蘇 畢節(jié) 股票 湖州 駐馬店 中山
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《python 用遞歸實(shí)現(xiàn)通用爬蟲解析器》,本文關(guān)鍵詞 python,用,遞歸,實(shí)現(xiàn),通用,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。