python——解析库lxml

安装lxml
pip3 install lxml 
初步使用

from lxml import etree
# 声明一段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>
'''
# 初始化,生成解析对象,并且etree模块可以自动修正HTML文本
html = etree.HTML(text)
# tostring()方法,输出自动修正后的HTML文本,返回bytes类型
result = etree.tostring(html)
# decode()方法转化为str类型
print(result.decode('utf-8'))

from lxml import etree
# 从文本文件中解析
html = etree.parse('./hello.html',etree.HTMLParser())
result = etree.tostring(html)
print(result.decode('utf-8'))

from lxml import etree
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"><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>
"""
html = etree.HTML(text)

# 获取所有<li>标签
html.xpath('//li')

# 获取<li>标签下所有class属性值
html.xpath('//li/@class')

# 获取<li>标签下href为link5.html的<a>标签
html.xpath('//li/a[@href='link5.html']')

# 获取 <li> 标签下的所有 class,不包括 <li>
html.xpath('//li/a//@class')

# 获取最后一个 <li><a> 的 href
html.xpath('//li[last()]/a/@href')

# 获取 class 为 bold 的标签名
result = html.xpath('//*[@class='bold']')
print(result[0].tag)

选取未知节点

Xpath通配符可用来选取未知的XML元素

<bookstore>

<book>
  <title>Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>

</bookstore>
通配符 描述
* 匹配任何元素节点
@* 匹配任何属性节点
node() 匹配任何类型节点

实例

路径表达式 结果
bookstore/* 选取bookstore元素的所有子元素
//* 选取文档中所有元素
//title[@*] 选取所有带有属性的 title 元素

更多用法详见静觅大神博文,以后在熟练中也会继续补充和自我理解。

猜你喜欢

转载自blog.csdn.net/hanfeixue11/article/details/80449186