lxml模塊學習

etree模塊
  • etree.HTML()
    將字符串類型轉換爲Element類型
    傳入字符串參數,返回element類型
from lxml import etree
text = '''
<div>
    <ul>
        <li class="item-1"><a>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>
'''
# 將字符串類型轉換爲Element類型
html = etree.HTML(text)
print(html)
  • etree.tostring()
    傳入element類型,返回二進制字符串類型,並且補全HTML代碼
# 承接上面代碼

# element類型轉化爲二進制字符串類型,並且自動補全html格式
str = etree.tostring(html)
# decode()解碼
print(str.decode())
  • element.xpath()
    字符串轉換爲element元素後的返回值,能調用xpath()函數進行匹配,並返回一個列表
# 承接上面代碼

# 返回一個包含篩選出來的元素的列表
l = html.xpath("//li[@class='item-1'/a/@href]")
print(l)

  • 生成字典

    提取信息後都需要生成字典,這樣查看信息會更加直觀

    • 愚蠢的方法
# 承接上面代碼

# 利用xpath()函數提取a標籤下的超鏈接,返回一個列表
hrefs = html.xpath("//li[@class='item-1'/a/href]")
# 繼續提取文本
texts = html.xpath("//li[@class='item-1'/a/text()]")
# 遍歷各自元素並放進字典
for href in hrefs:
    item = {}
    item["href"] = href
    item["text"] = texts[hrefs.index(href)]
    print(item)
  • 完整代碼
from lxml import etree
text = '''
<div>
    <ul>
        <li class="item-1"><a>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>
'''
# 轉換爲element類型
html = etree.HTML(text)
# 提取信息,返回來包含element對象的列表
els = html.xpath("//li[@class='item-1']")
# 遍歷列表
x1 = "./a/text()"
x2 = "./a/@href"
for el in els:
    item = {}
    item["title"] = el.xpath(x1)[0] if len(el.xpath(x1)) > 0 else None
    item["href"] = el.xpath(x2)[0] if len(el.xpath(x2)) > 0 else None
    print(item)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章