这是一份 XPath 选择器备忘单,其中列出了常用的 XPath 定位方法和 CSS 选择器
XPath 即为 XML 路径语言(XML Path Language),它是一种用来确定XML文档中某部分位置的计算机语言。
类似路径 语法识别和导航 XML 文档中的节点在 Firefox 或 Chrome 控制台中测试:
$x('/html/body')
$x('//h1')
$x('//h1')[0].innerText
$x('//a[text()="XPath"]')[0].click()
| Xpath | CSS |
|---|---|
//*[@id="id"] | #id |
//*[@class="class"] | .class |
//input[@type="submit"] | input[type="submit"] |
//a[@id="abc"][@for="xyz"] | a#abc[for="xyz"] |
//a[@rel] | a[rel] |
//a[starts-with(@href, '/')] | a[href^='/'] |
//a[ends-with(@href, '.pdf')] | a[href$='pdf'] |
//a[contains(@href, '://')] | a[href*='://'] |
//a[contains(@rel, 'help')] | a[rel~='help'] |
contains() # font[contains(@class,"head")]
starts-with() # font[starts-with(@class,"head")]
ends-with() # font[ends-with(@class,"head")]
concat(x,y)
substring(str, start, len)
substring-before("01/02", "/") #=> 01
substring-after("01/02", "/") #=> 02
translate()
normalize-space()
string-length()
| Axis | Abbrev | Notes |
|---|---|---|
ancestor | 选择当前节点的所有祖先(父母、祖父母等) | |
ancestor-or-self | 选择当前节点所有祖先(父、祖父等)和当前节点本身 | |
attribute | @ | @href 是 attribute::href 的缩写 |
child | div 是 child::div 的缩写 | |
descendant | 选择当前节点的所有后代(子、孙等) | |
descendant-or-self | // | // 是 /descendant-or-self::node()/的缩写 选择当前节点和当前节点本身的所有后代(子、孙等) |
namespace | 选择当前节点的所有命名空间节点 | |
self | . | . 是 self::node() 的缩写,选择当前节点 |
parent | .. | .. 是 parent::node() 的缩写,选择当前节点的父节点 |
following | 选择文档中当前节点结束标记之后的所有内容 | |
following-sibling | 选择当前节点之后的所有兄弟节点 | |
preceding | 选择文档中出现在当前节点之前的所有节点,除了祖先、属性节点和命名空间节点 | |
preceding-sibling | 选择当前节点之前的所有兄弟节点 |
您还可以使用其他轴。