lxml
用法源自 lxml python
官方文檔,更多內容請直接參閱官方文檔
HTML 示例代碼
text = '''
<div>
<ul>
<li class="item-0"><a href="link1.html">first item</a></li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-inactive"><a href="link3.html">third item</a></li>
<li class="item-1"><a href="link4.html">fourth item</a></li>
<li class="item-0"><a href="link5.html">fifth item</a>
</ul>
</div>
'''
小試牛刀
使用 lxml
的 etree
庫,將其打印出來
# 導入 lxml etree 庫
from lxml import etree
# 獲取 html 內容 元素
htmlEmt = etree.HTML(text)
# 將內容元素轉換爲字符串
result = etree.tostring(htmlEmt)
# utf-8 格式輸出
print(result.decode("utf-8"))
打印結果爲:
<html><body><div>
<ul>
<li class="item-0"><a href="link1.html">first item</a></li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-inactive"><a href="link3.html">third item</a></li>
<li class="item-1"><a href="link4.html">fourth item</a></li>
<li class="item-0"><a href="link5.html">fifth item</a></li>
</ul>
</div></body></html>
lxml 有自動修正 HTML 代碼的功能
文件讀取
利用 parse 方法來讀取文件
文件名:text.xml
內容:
<div>
<ul>
<li class="item-0"><a href="link1.html">first item</a></li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>
<li class="item-1"><a href="link4.html">fourth item</a></li>
<li class="item-0"><a href="link5.html">fifth item</a></li>
</ul>
</div>
from lxml import etree
# text.xml 是一個 xml 文件,並在當前文件同目錄下
htmlEmt = etree.parse('text.xml')
# pretty_print: 優化輸出
result = etree.tostring(htmlEmt, pretty_print=True)
# 輸出
print(result)
同樣可以得到相同的結果
XPath實例測試
以上一段 text.xml
文件爲例
獲取所有的 <li>
標籤
from lxml import etree
# 獲取文件元素
htmlEmt = etree.parse('text.xml')
# 獲取所有的 <li> 標籤
result = htmlEmt.xpath('//li')
print(result)
# 獲取標籤數量
print(len(result))
# 取出第一個 li 標籤
print(result[0])
輸出結果:
[<Element li at 0x1023fc0c8>, <Element li at 0x1023fc108>, <Element li at 0x1023fc148>, <Element li at 0x1023fc188>, <Element li at 0x1023fc1c8>]
5
<Element li at 0x1023fc0c8>
獲取 <li>
標籤的所有 class
result = htmlEmt.xpath('//li/@class')
print(result)
輸出結果:
['item-0', 'item-1', 'item-inactive', 'item-1', 'item-0']
獲取 <li>
標籤下 href
爲 link1.html
的 <a>
標籤
result = htmlEmt.xpath('//li/a[@href="link1.html"]')
print(result)
print(result[0].text)
輸出結果:
[<Element a at 0x1023fc208>]
first item
獲取 <li>
標籤下的所有 <span>
標籤
因爲 /
是用來獲取子元素的,而 <span>
並不是 <li>
的子元素,所以,要用雙斜槓
result = html.xpath('//li//span')
print(result)
print(result[0].text)
輸出結果:
[<Element span at 0x1023fc0c8>]
third item
獲取 <li>
標籤下的所有 class
,不包括 <li>
標籤的 class
result = html.xpath('//li/a//@class')
print(result)
輸出結果:
['bold']
獲取最後一個 <li>
的 <a>
的 href
result = html.xpath('//li[last()]/a/@href')
print(result)
輸出結果:
['link5.html']
獲取倒數第二個元素的內容
result = html.xpath('//li[last()-1]/a')
print(result[0].text)
輸出結果:
fourth item
獲取 class
爲 bold
的標籤名
result = html.xpath('//*[@class="bold"]')
print(result[0].tag)
print(result[0].text)
輸出結果:
span
third item