XPath,是在 XSLT 标准中的主要元素,用于在 XML 文档中选择元素,我们可以理解为元素选择器(功能上与 CSS Selectors 类似)。
我们感觉 XPath 比 CSS Selector 好用,也可能是我们不熟悉 CSS 选择器,也可能是我们的场景使然。
学习路线(Learning Roadmap)
按照 w3school.com 章节顺序进行学习即可:
1)形成 XPath 基本认识:XPath Tutorial
2)理解基本概念,比如 Parent、Children、Ancestors 等等:XPath Nodes
3)学习 XPath 语法:XPath Syntax
4)相对于当前节点定位其他节点:XPath Axes
5)使用操作符进行判断:XPath Operators
6)学习示例:XPath Examples
调试 XPath 查询(验证 XPath 查询是否正确)
方法一、通过浏览器直接获取
我们可以使用 Chrome / Firefox 快速获取元素的 XPath 地址。下面是 Chrome 的方法:
Inspect => Right click on the node => Copy => Copy XPath
方法二、使用 Console 调试
在 Chrome / Firefox 的 Console 中,使用 $x('your-xpath-query') 函数,
比如:通过 $x("//img") 选择所有图片
常用 XPath 查询(在我们工作中比较常用)
获取在兄弟元素中的元素
html – XPath:: Get following Sibling – Stack Overflow
获取在 div 的后续所有兄弟(sibling)元素中的 input 元素:
//div/following-sibling::input
获取某个元素的父级元素
获取 <input id=”commitBtn” /> 的父级元素:
//parent::input[@id='commitBtn']
根据属性值的内容定位属性
XPath with regex match on an attribute value – Stack Overflow
How to use not contains() in xpath? – Stack Overflow
定位 href 属性包含 doubles 字符串的 a 标签:
//a[contains(@href, ' doubles ')]
定位 href 属性不包含 doubles 字符串的 a 标签:
//a[not(contains(@href, ' doubles '))]
根据元素的位置进行定位
xml – Get Nth child of a node using xpath – Stack Overflow
xpath – XSLT getting last element – Stack Overflow
定位在 ul 中的 前三个 li 元素:
//ul[@id='thread_list']/li[position()<=3]
在所有匹配元素中,获取最后一个元素:
(//element[@name='D'])[last()]
定位包含某个属性的元素
xml – XPath: How to check if an attribute exists? – Stack Overflow
定位具有 foo 属性的 span 标签:
//span[@foo]
定位包含某种元素的元素
html – Selenium – XPATH – Searching for element by innerHTML – Stack Overflow
xml – Can XPath return only nodes that have a child of X? – Stack Overflow
定位所有包含 span[@class='split_line'] 的 div 元素:
//div[descendant::span[@class='split_line']]
定位子元素 span[@class='split_line'] 的 div 元素:
//div[span[@class='split_line']]
参考文献
w3schools.com/XPath Tutorial
XPath – XML Path Language (XPath)
Scrapy/Docs » Selectors
Is there a way to get the XPath in Google Chrome? – Stack Overflow
How to validate XPath using Firefox Web Developer Plugin? – Stack Overflow