【Python网络爬虫】150讲轻松搞定Python网络爬虫付费课程笔记 篇七——爬虫解析库XPath

1. 了解 XPath

1.1 什么是XPath呢?

XPath是一门在XML和HTML文档中查找信息的语言,可以用来在XML和HTML文档中对元素和属性进行遍历。

1.2 XPath开发工具

chrome插件 XPath Helper

Firefox插件 Try XPath

1.3 XPath 节点

有七种类型的节点:元素、属性、文本、命名空间、处理指令、注释以及文档(根)节点。

XML文档是被作为节点树来对待。树的根被称为文档节点或根节点。

 

2. XPath语法

2.1 路径表达式

使用路径表达式来选取XML文档中的节点或节点集。

选取多个路径用 | 运算符 

2.2 谓语 

谓语用来查找特定的节点或包含某个指定的值的节点,被嵌在方括号【】中,注意【】中的序号从1开始。

2.3 通配符

*表示通配符

2.4 运算符

3. LXML 库

lxml 是一个HTML/XML的解析器,主要功能是如何解析和提取HTML/XML数据。

3.1 基本使用

3.1.1 解析代码

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">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>
'''

#将字符串解析未html文档
html = etree.HTML(text)
print(html)

#字符串序列化html
result = etree.tostring(html).decode('utf-8')
print(result)

3.1.2 从文件中读取HTML代码:

from lxml import etree

#读取
html2 = etree.parse('text.html')
result2 = etree.tostring(html2).decode('utf-8')
print(result2)

在使用parse 读取HTML文件时,注意html文件里标签的完整,否则会报错。

 

3.2 在lxml中使用XPath语法

from lxml import etree

html = etree.parse('text.html')
#获取所有li
result1 = html.xpath('//li')
# print(result)
for i in result1:
    print(etree.tostring(i).decode('utf-8'))

# 获取所有li元素下所有class 属性值
result2 = html.xpath('//li/@class')
print(result2)

# 获取所有li元素下href = "www.baidu.com"的a
result3 = html.xpath('//li/a[@href="www.baidu.com"]')
print(result3)

# 获取所有li元素下span标签 用//
result4 = html.xpath('//li//span')
print(result4)

# 获取所有li元素下a标签的所有class
result5 = html.xpath('//li/a//@class')
print(result5)

# 获取最后一个li元素下a标签的href对应的值
result6 = html.xpath('//li[last()]/a/@href')
print(result6)

# 获取最后二个li元素下内容
result7 = html.xpath('//li[last()-1]/a')
print(result7)
print(result7[0].text)

# 获取最后二个li元素下内容 第二种方式
result7 = html.xpath('//li[last()-1]/a/text()')
print(result7)
# print(result7[0].text)

猜你喜欢

转载自blog.csdn.net/weixin_44566432/article/details/108593014
今日推荐