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)