Python工具之lxml解析html

lxml解析

from lxml import etree
text='''
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a  class="sister" id="link1"><!-- Elsie --></a>,
<a  class="sister" id="link2">Lacie</a> and
<a  class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
'''

html=etree.HTML(text)
#讀取文件
#html=etree.parse('test.html')
result=etree.tostring(html)
print(result)

輸出結果,補全了html的標簽

<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a  class="sister" id="link1"><!-- Elsie --></a>,
<a  class="sister" id="link2">Lacie</a> and
<a  class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
</body></html>

獲取a標簽和a的class

print html.xpath('//a')
#[<Element a at 0x10bdc0cb0>, <Element a at 0x10bdc0c68>, <Element a at 0x10bdc0b90>]
print html.xpath('//a/@href')
#['http://example.com/elsie', 'http://example.com/lacie', 'http://example.com/tillie']
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,937評論 18 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,334評論 25 708
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,765評論 18 399
  • 愛情和友情,到底哪個重要?在不同人眼里對這個問題的答案也是不同的,有些人認為愛人是陪伴自己一生的人,就應該好好珍惜...
    戀星座閱讀 311評論 0 0