XPath
XPath(XML/HTML Path Language): Query language for XML/HTML.
XPath 表达式构成
| Component | Example |
|---|---|
| 分隔符 | /, // |
| 节点(标签) | div, tr, td … |
| 节点(属性) | @class,@id … |
| 节点(文本) | text(),comment() … |
| 限定符/谓语 | [] |
| 轴 | following-sibling:: … |
| 函数 | starts-with() … |
| 操作符 | and, or, >=, <= … |
如何使用 XPath
- Chrome Elements

- Chrome Console

- Scrapy shell

XPath 案例
| XPath | Comment |
|---|---|
| //ul/li/a | 纯节点 |
| //button/text()[.=‘Submit’] | 限定符 |
| //a[@id=“abc”][@for=“xyz”] | 多限定符 |
| //a[@name or @href] | 操作符 |
| //a[starts-with(@href, “/”)] | 函数 |
| //ul[count(li) > 2 and li[ends-with(@class, “active”)]] | 复合条件 |
| //ul/li[last()] | 位置 |
| //h1/following-sibling::ul | 轴 |
| //div[count(./div)=2] | //tr[count(./td)=2] | 合集 |
XPath 要注意的 11 个点
- 返回的是节点集合。
- text() 也是节点,可以限定。
- [] 可联结(Chainable:
[][]), 可嵌套(Nestable:[[]])。 - 路径表达式可以通过 “|” 获取合集。
- source code 里 tbody 标签可能不存在。
- 善用函数
substring-before(XPath, "split_str"),concat(XPath, XPath)。 - 注意函数的作用域,往往只作用于节点集的第一个节点。
- 当前节点它是一个引用,依然可以搜索整棵树。
- 可结合 re 的功能。
- 强烈推荐 Python package parsel,它还支持 JMESPath。
- 如果是 XML 类型,需要声明 namespace 及替换没有 namespace 的 soap。