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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值