Xpath

fansichao 2021-10-23 16:25:17
Categories: Tags:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from lxml import etree

web_data="xxxx<div>xxx</div>"
html = etree.HTML(web_data)

# 打印html
result = etree.tostring(html, pretty_print=True).deocde('utf-8')

路径表达式说明
- nodename 选取此节点的所有子节点。
- / 绝对路径 从根节点选取。
- // 相对路径 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。
- . 选取当前节点。
- .. 选取当前节点的父节点。
- @ 选取属性。

# 样例
/html/body/div/ul/li/a/text()
# 获取a标签的href属性
//ul/li/a/@href
# 获取a标签属性href=xxx.html的内容
//ul/li/a[@href="xxx.html"/text()]
# 查询倒数第二个li中的内容
//li[last()-1]/a/text()

参考链接: