Blogs (码码要洗手)

XPath

XPath(XML/HTML Path Language): Query language for XML/HTML.

视频解说点这里

XPath 表达式构成

ComponentExample
分隔符/, //
节点(标签)div, tr, td …
节点(属性)@class,@id …
节点(文本)text(),comment() …
限定符/谓语[]
following-sibling:: …
函数starts-with() …
操作符and, or, >=, <= …

如何使用 XPath

  • Chrome Elements Elements
  • Chrome Console Console
  • Scrapy shell Scrapy

XPath 案例

XPathComment
//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 个点

  1. 返回的是节点集合。
  2. text() 也是节点,可以限定。
  3. [] 可联结(Chainable: [][]), 可嵌套(Nestable: [[]])。
  4. 路径表达式可以通过 “|” 获取合集。
  5. source code 里 tbody 标签可能不存在。
  6. 善用函数 substring-before(XPath, "split_str"), concat(XPath, XPath)
  7. 注意函数的作用域,往往只作用于节点集的第一个节点。
  8. 当前节点它是一个引用,依然可以搜索整棵树。
  9. 可结合 re 的功能。
  10. 强烈推荐 Python package parsel,它还支持 JMESPath。
  11. 如果是 XML 类型,需要声明 namespace 及替换没有 namespace 的 soap。

参考