用python的urllib2庫實現的獲取到網頁資料之後,使用lxml對獲取的網頁進行資料抓取。
1.匯入包 from lxml import etree
2.page = etree.html(html) 或者 page = etree.html(html.decode('utf-8'))
3.對element物件(page)使用xpath篩選,返回乙個列表(裡面的元素也是element)
舉例:
測試內容二
測試內容三
測試內容四
谷歌阿里
解析html
from lxml import etree
page = etree.html(html.decode('utf-8'))
獲取標籤
# a標籤
tags = page.xpath(u'/html/body/a')
print(tags)
# html 下的 body 下的所有 a
# 結果[, ...]
/html 整個網頁的根目錄
/html/body/a 獲取整個網頁標籤下所有標籤
//a 獲取html下所有a標籤,在本例中功能同上(所有a標籤都放在body下,別的地方沒有)
/descendant::a 等價於 //a descendant::字首可紙袋任意多層中間節點,也可以省略成乙個「 /」
/html/body/*/a 表示取出body下第二級的所有a標籤,不管它的上級是什麼標籤,『*』可以代表所有的節點名
獲取head裡面的標籤要特別一點 比如//html/head/* 或者//html/head/title
獲取節點(標籤)屬性:
for taga in tags:
print(taga.attrib)
# 獲取屬性:
print(taga.get('href'))
# 獲取某一屬性:
print(taga.text)
# 獲取文字: 阿里
利用屬性篩選標籤
# 直接定位到
hs = page.xpath("//h1[@class='heading']")
for h in hs:
print(h.values())
print(h.text)
# 列印結果:
# ['heading']
# 測試內容一
屬性可以寫@name,@id,@value,@src,@href...
如果沒有屬性,也可以使用text()(表示標籤內包含的內容)和positon()(獲取節點的位置)
示例:a[position()=2] 表示取得第二個a節點,可以被省略為a[2]
需要注意數字定位和過濾條件的順序
/body/a[5][@name='hello'] 表示取下第五個a標籤,並且name必須是hello,否則為空
/body/a[@name='hello'][5] 表示取body下第五個name為hello的a標籤
preceding-sibling::和 following-sibling::
preceding-sibling::字首表示同一層的上乙個節點
following-sibling::字首表示同一層的下乙個節點
示例
//body//following-sibling::a 同層下乙個a標籤
//body/h1/preceding-sibling::* 所有h1上所有h1同級的子標籤
tail獲取特殊內容tail的意思是結束節點前面的內容,就是和標籤中間的內容
如果script與style標籤之間的內容影響解析頁面,或者頁面很不規則,可以使用lxml.html.clean模組。模組 lxml.html.clean 提供 乙個cleaner 類來清理 html 頁。它支援刪除嵌入或指令碼內容、 特殊標記、 css 樣式注釋或者更多。
cleaner = cleaner(style=true, scripts=true,page_structure=false, safe_attrs_only=false)
print cleaner.clean_html(html)
注意,page_structure,safe_attrs_only為false時保證頁面的完整性,否則,這個cleaner會把你的html結構與標籤裡的屬性都給清理了。使用cleaner類要十分小心,小心擦槍走火。
忽略大小寫可以:
page = etree.html(html)
keyword_tag = page.xpath("//meta[translate(@name,'abcdefghjiklmnopqrstuvwxyz', 'abcdefghjiklmnopqrstuvwxyz')='keywords']")
python爬蟲網頁解析之lxml模組
windows系統下的安裝 方法一 pip3 install lxml pip3 install lxml 4.2.1 cp36 cp36m win amd64.whl 檔案所在的路徑 linux下安裝 方法一 pip3 install lxml 方法二 yum install y epel rel...
lxml解析xml檔案
最近在工作中需要從多個xml檔案中選出一些節點合成乙個新的xml檔案,首先想到的使用python自帶的xml.etree.elementtree模組,但是發現合併後的檔案中原來的cdata部分不對,括號和引號都被轉義了,沒有和原來保持一致,elementtree模組解決不了這個問題,我就想會不會有第...
lxml 解析錯誤ValueError
一 lxml解析錯誤 html etree.html xml 報錯的 行 valueerror unicode strings with encoding declaration are not supported.please use bytes input or xml fragments wi...