# Xpath

# 一、节点概念

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>网页名</title>
</head>
<body>
    <div>
        div-text
        <span>span-text</span>
        <a>a-text</a>
        <p>p-text</p>
    </div>
    <table>
        <tr>
            <th>Heading</th>
            <th>Another Heading</th>
        </tr>
        <tr>
            <td>row 1, cell 1</td>
            <td>row 1, cell 2</td>
        </tr>
        table-text-2
    </table>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# 1. ...

. 代表当前节点

# 获取到div
print(html.xpath('/html/body/div/./.'))
1
2

.. 代表父节点

# 获取到body
print(html.xpath('/html/body/div/..'))
1
2

# 2.///

/ 代表子集某个节点,一层的关系

# 获取到div下面的table标签
print(html.xpath('/html/body/div/../table'))
1
2

// 代表子集某个节点,涉及多层关系

# 获取了子孙级的节点
print(html.xpath('/html//td'))
1
2

# 二、标签检索

1、获取节点文本输出

print(html.xpath('/html/head/title/text()'))
['网页名']
1
2
更新时间: 2/4/2024, 10:22:42 PM