lxml的另一種用法

2021-08-03 23:42:16 字數 1106 閱讀 8751

python中lxml庫是乙個十分強大的xml解析庫,最近在看《白帽子將web掃瞄》這本書的時候,裡面提供了一種不同於以往的用法,因此在這將這個方法記錄下來

傳統的lxml庫的使用方法類似於下面這樣:

from lxml import etree

tree = etree.html(html) #假定html是乙個html文字字串

tag_a = tree.xpath("//a")

from lxml import etree

class

htmlparser:

def__init__

(self):

#在函式中定義一些屬性,比如解析出來的url或者希望儲存的中間變數

parser = etree.htmlparser(target=self, recover=true, encoding='utf-8')

try:

etree.fromstring(self._html, parser)

except valueerror:

pass

defstart

(self, tag, attrbs):

meth = getattr(self, "_handle_" + tag + "_tag_start")

meth(tag, attrbs)

def_handle_a_tag_start

(self, tag, attrbs):

#dosomething

pass

defend

(tag):

meth = getattr(self, "_handle_" + tag + "_tag_end")

meth(tag, attrbs)

在呼叫fromstring()將字串轉化為dom時每當進入乙個標籤開始位置將呼叫start函式,而當即將離開該標籤時呼叫end函式,start函式傳入標籤名tag和標籤的屬性列表attrbs。在這兩個函式中使用getattr函式獲取類中對應名稱的函式,這個函式名稱以標籤名作為唯一標識,如果有該函式則呼叫,這樣根據不同函式的呼叫就知道到了哪個標籤裡面,針對不同的標籤編寫不同的處理**即可。

using的另一種用法

mail zsc771120 yahoo.先看下面的程式碼 using form arg arg new form arg this.ip,this.port,this.limit 我以前經常使用 using system 或者 using system.io 等加入新namespace,上面的程式...

模板函式的另一種用法

今天遇到了乙個bug,具體如下 type a struct type b struct此時在controller檔案中this.data lists blist,即通過模板傳遞 b形式的slice,在html檔案中通過模板呼叫 位置1 位置2 output somrthing with結束標誌 在上...

另一種尊重

上中學的時候,有一節課印象非常深刻。老師問我們如果無意闖入乙個房間,發現房間裡有一位女士正在洗澡,這時應該怎麼辦?有同學回答就當什麼也沒看見,退出房間。還有同學回答 說聲對不起!女士。然後退出去。老師笑了笑說,還有更好的答案,那就是 對不起,先生!有一對結婚多年的夫妻,有一次出差在外的妻子有一件急事...