之前在使用java編寫爬蟲解析html的時候習慣用jsoup,用python寫爬蟲的時候習慣用beautifulsoup
兩個都屬于用起來比較簡單但是效率相對于其他的庫來說比較低下的庫,現在學習python下的lxml的使用
這裡将lxml的文法和beautifulsoup做一個對比
1.加載html内容
beautifulsoup實作
>>> data = open("f:\\test5.html","rb").read()
>>> html = data.decode("utf-8","ignore")
>>> from bs4 import BeautifulSoup
>>> bs = BeautifulSoup(html,"lxml")
lxml實作(從檔案中讀取html的部分省略)
>>> from lxml import etree
>>> html = etree.HTML(html)
2.内容的解析
要使用lxml,需要首先學習Xpath的文法
在為w3cschool中找到的資料如下
XPath 使用路徑表達式來選取 XML 文檔中的節點或節點集。節點是通過沿着路徑 (path) 或者步 (steps) 來選取的。
我的了解是,xpath将html或者xml文檔當做一個檔案來對待,每個節點代表不同的路徑
"/"表示文檔根節點(即文檔本身)而/html表示最外層的文檔節點
如果要定位一個标簽,與定位一個檔案類似,可以使用相對路徑或者絕對路徑
絕對路徑即給出從/html的外層标簽到我們需要定位的标簽所經過的所有路徑(與檔案絕對路徑一樣的)
比如我們要找一個文檔中的所有a标簽,用絕對路徑定位就是
u"/html/body/a"
例如:
>>> hrefs = html.xpath(u"/html/body/link")
>>> hrefs
[<Element link at 0x3f451c0>, <Element link at 0x4c2bf08>, <Element link at 0x4c2be68>, <Element link at 0x4c2bee0>, <Element link at 0x4c2beb8>, <Element link at 0x4c2be90>, <Element link at 0x4c2bd50>]
可以看出,使用絕對路徑,找到的是body下的所有link,但是不會找子節點的子節點
相對路徑
u//a
>>> hrefs = html.xpath(u"//a")
>>> hrefs
[<Element a at 0x4c39648>, <Element a at 0x4c2bb20>, <Element a at 0x4c2beb8>, <Element a at 0x4c2be90>, <Element a at 0x4c2bee0>, <Element a at 0x4c2bf08>, <Element a at 0x4c2be68>, <Element a at 0x4c2bf80>, <Element a at 0x4c2bf30>, <Element a at 0x4c2bfa8>, <Element a at 0x4c2bfd0>, <Element a at 0x4c32030>, <Element a at 0x4c32058>, <Element a at 0x4c32080>, <Element a at 0x4c320a8>, <Element a at 0x4c320d0>, <Element a at 0x4c320f8>, <Element a at 0x4c32120>, <Element a at 0x4c32148>, <Element a at 0x4c32170>, <Element a at 0x4c32198>, <Element a at 0x4c321c0>, <Element a at 0x4c321e8>, <Element a at 0x4c32210>, <Element a at 0x4c32238>, <Element a at 0x4c32260>, <Element a at 0x4c32288>, <Element a at 0x4c322b0>, <Element a at 0x4c322d8>, <Element a at 0x4c32300>, <Element a at 0x4c32350>, <Element a at 0x4c32378>, <Element a at 0x4c323a0>, <Element a at 0x4c323c8>, <Element a at 0x4c323f0>, <Element a at 0x4c32418>, <Element a at 0x4c32440>, <Element a at 0x4c32468>, <Element a at 0x4c32490>, <Element a at 0x4c324b8>, <Element a at 0x4c324e0>, <Element a at 0x4c32508>, <Element a at 0x4c32530>, <Element a at 0x4c32558>, <Element a at 0x4c32580>, <Element a at 0x4c325a8>, <Element a at 0x4c325d0>, <Element a at 0x4c325f8>, <Element a at 0x4c32620>, <Element a at 0x4c32648>, <Element a at 0x4c32670>, <Element a at 0x4c32698>, <Element a at 0x4c326c0>, <Element a at 0x4c326e8>, <Element a at 0x4c32710>, <Element a at 0x4c32738>, <Element a at 0x4c32760>, <Element a at 0x4c32788>
可以看到,相對路徑找的是所有的a節點
如何定位我們需要的唯一進制素呢?
與beautifulsoup類似,用标簽的屬性來定義,不過xpath有他特有的文法
利用classname來定位元素
使用beautifulsoup:href = bs.find_all("a",class_="classname")
使用lxml:href = html.xpath(u"//a[@class='classname']")
可以看出xpath定位特定的标簽文法是u"路徑(相對路徑或者絕對路徑[@屬性='屬性名'])"
如果沒有屬性呢?
可以使用标簽之間的文字來定位(bs中标簽的text屬性)
u"路徑(相對路徑或者絕對路徑[@text='content'])"
在xpath中*可以代表任意元素(類似于正規表達式)
例如u"/html/bodyp"表示的是body節點的子節點的子節點中的p節點