xpath: update

This commit is contained in:
Rico Sta. Cruz 2017-08-30 06:50:54 +08:00
parent 7e4b7636d5
commit 3d70f16b77
No known key found for this signature in database
GPG Key ID: CAAD38AE2962619A
1 changed files with 146 additions and 108 deletions

248
xpath.md
View File

@ -1,11 +1,13 @@
--- ---
title: Xpath title: Xpath
category: HTML category: HTML
layout: default-ad layout: 2017/sheet
tags: [Featured] tags: [Featured]
weight: -5 weight: -5
--- ---
## Selectors
### Descendant selectors ### Descendant selectors
| CSS | Xpath | ? | | CSS | Xpath | ? |
@ -18,7 +20,7 @@ weight: -5
| ---- | ---- | -- | | ---- | ---- | -- |
| `:root` | `/` | [?](#prefixes) | | `:root` | `/` | [?](#prefixes) |
| `:root > body` | `/body` | | | `:root > body` | `/body` | |
{:.greycode.no-head.xp} {: .xp}
### Attribute selectors ### Attribute selectors
@ -33,7 +35,7 @@ weight: -5
| `a[href^='/']` | `//a[starts-with(@href, '/')]` | [?](#string-functions) | | `a[href^='/']` | `//a[starts-with(@href, '/')]` | [?](#string-functions) |
| `a[href$='pdf']` | `//a[ends-with(@href, '.pdf')]` | | | `a[href$='pdf']` | `//a[ends-with(@href, '.pdf')]` | |
| `a[href~='://']` | `//a[contains(@href, '://')]` *...[kinda](#class-check)* | | | `a[href~='://']` | `//a[contains(@href, '://')]` *...[kinda](#class-check)* | |
{:.greycode.no-head.xp} {: .xp}
### Order selectors ### Order selectors
@ -45,7 +47,7 @@ weight: -5
| `li#id:first-child` | `//li[@id="id"][1]` | | | `li#id:first-child` | `//li[@id="id"][1]` | |
| `a:first-child` | `//a[1]` | | | `a:first-child` | `//a[1]` | |
| `a:last-child` | `//a[last()]` | | | `a:last-child` | `//a[last()]` | |
{:.greycode.no-head.xp} {: .xp}
### Siblings ### Siblings
@ -54,7 +56,7 @@ weight: -5
| `h1 ~ ul` | `//h1/following-sibling::ul` | [?](#using-axes) | | `h1 ~ ul` | `//h1/following-sibling::ul` | [?](#using-axes) |
| `h1 + ul` | `//h1/following-sibling::ul[1]` | | | `h1 + ul` | `//h1/following-sibling::ul[1]` | |
| `h1 ~ #id` | `//h1/following-sibling::[@id="id"]` | | | `h1 ~ #id` | `//h1/following-sibling::[@id="id"]` | |
{:.greycode.no-head.xp} {: .xp}
### jQuery ### jQuery
@ -64,7 +66,7 @@ weight: -5
| `$('li').closest('section')` | `//li/ancestor-or-self::section` | | | `$('li').closest('section')` | `//li/ancestor-or-self::section` | |
| `$('a').attr('href')` | `//a/@href` | [?](#steps) | | `$('a').attr('href')` | `//a/@href` | [?](#steps) |
| `$('span').text()` | `//span/text()` | | | `$('span').text()` | `//span/text()` | |
{:.greycode.no-head.xp} {: .xp}
### Other things ### Other things
@ -78,59 +80,66 @@ weight: -5
| Has children (specific) | `//ul[li]` | | | Has children (specific) | `//ul[li]` | |
| Or logic | `//a[@name or @href]` | [?](#operators) | | Or logic | `//a[@name or @href]` | [?](#operators) |
| Union (joins results) | `//a | //div` | [?](#unions) | | Union (joins results) | `//a | //div` | [?](#unions) |
{:.greycode.no-head.xp} {: .xp}
<style> <style>
/* ensure tables align */ /* ensure tables align */
table.xp {table-layout: fixed;} table.xp {table-layout: fixed;}
table.xp tr>:nth-child(1) {width: 30%;} table.xp tr>:nth-child(1) {width: 35%;}
table.xp tr>:nth-child(2) {width: auto;} table.xp tr>:nth-child(2) {width: auto;}
table.xp tr>:nth-child(3) {width: 10%; text-align:right;} table.xp tr>:nth-child(3) {width: 10%; text-align:right;}
</style> </style>
### Class check ### Class check
Xpath doesn't have the "check if part of space-separated list" operator, so this is the workaround ([source](http://pivotallabs.com/xpath-css-class-matching/)):
```sh ```bash
//div[contains(concat(' ',normalize-space(@class),' '),' foobar ')] //div[contains(concat(' ',normalize-space(@class),' '),' foobar ')]
``` ```
{:.light}
Xpath doesn't have the "check if part of space-separated list" operator, so this is the workaround ([source](http://pivotallabs.com/xpath-css-class-matching/)).
Expressions Expressions
----------- -----------
### Steps and axes
| `//` | `ul` | `/` | `a[@id='link']` |
| Axis | Step | Axis | Step |
{: .-css-breakdown}
### Prefixes ### Prefixes
| Prefix | Example | What |
| --- | --- | --- |
| `//` | `//hr[@class='edge']` | Anywhere |
| `./` | `./a` | Relative |
| `/` | `/html/body/div` | Root |
{: .-headers}
Begin your expression with any of these. Begin your expression with any of these.
| Prefix | Example |
| --- | --- |
| `//` *anywhere* | `//hr[@class='edge']` |
| `./` *relative* | `./a` |
| `/` *root* | `/html/body/div` |
{:.greycode.no-head}
### Axes ### Axes
| Axis | Example | What |
| --- | --- | --- |
| `/` | `//ul/li/a` | Child |
| `//` | `//[@id="list"]//a` | Descendant |
{: .-headers}
Separate your steps with `/`. Use two (`//`) if you don't want to select direct children. Separate your steps with `/`. Use two (`//`) if you don't want to select direct children.
| Axis | Example |
| --- | --- |
| `/` *child* | `//ul/li/a` |
| `//` *descendant* | `//[@id="list"]//a` |
{:.greycode.no-head}
### Steps ### Steps
A step may have an element name (`div`) and [predicates](#predicate) (`[...]`). Both are optional.
```sh ```bash
//div //div
//div[@name='box'] //div[@name='box']
//[@id='link'] //[@id='link']
``` ```
{:.light}
They can also be these other things. A step may have an element name (`div`) and [predicates](#predicate) (`[...]`). Both are optional.
They can also be these other things:
```sh ```bash
//a/text() #=> "Go home" //a/text() #=> "Go home"
//a/@href #=> "index.html" //a/@href #=> "index.html"
//a/* #=> All a's child elements //a/* #=> All a's child elements
@ -139,50 +148,51 @@ They can also be these other things.
Predicates Predicates
---------- ----------
### Predicates (`[...]`) ### Predicates
Restricts a nodeset only if some condition is true. They can be chained.
```sh ```bash
//div[true()] //div[true()]
//div[@class="head"] //div[@class="head"]
//div[@class="head"][@id="top"] //div[@class="head"][@id="top"]
``` ```
{:.light}
Restricts a nodeset only if some condition is true. They can be chained.
### Operators ### Operators
```bash
# Comparison
//a[@id = "xyz"]
//a[@id != "xyz"]
//a[@price > 25]
```
```bash
# Logic (and/or)
//div[@id="head" and position()=2]
//div[(x and y) or not(z)]
```
Use comparison and logic operators to make conditionals. Use comparison and logic operators to make conditionals.
```sh
# Comparison
//a[@id = "xyz"]
//a[@id != "xyz"]
//a[@price > 25]
```
```sh
# Logic (and/or)
//div[@id="head" and position()=2]
//div[(x and y) or not(z)]
```
### Using nodes ### Using nodes
```bash
# Use them inside functions
//ul[count(li) > 2]
//ul[count(li[@class='hide']) > 0]
```
```bash
# This returns `<ul>` that has a `<li>` child
//ul[li]
```
You can use nodes inside predicates. You can use nodes inside predicates.
```sh
# Use them inside functions
//ul[count(li) > 2]
//ul[count(li[@class='hide']) > 0]
```
```sh
# This returns `<ul>` that has a `<li>` child
//ul[li]
```
### Indexing ### Indexing
Use `[]` with a number, or `last()` or `position()`.
```sh ```bash
//a[1] # first <a> //a[1] # first <a>
//a[last()] # last <a> //a[last()] # last <a>
//ol/li[2] # second <li> //ol/li[2] # second <li>
@ -190,51 +200,58 @@ Use `[]` with a number, or `last()` or `position()`.
//ol/li[position()>1] # :not(:first-child) //ol/li[position()>1] # :not(:first-child)
``` ```
### Chaining order Use `[]` with a number, or `last()` or `position()`.
Order is significant, these two are different.
```sh ### Chaining order
```bash
a[1][@href='/'] a[1][@href='/']
a[@href='/'][1] a[@href='/'][1]
``` ```
Order is significant, these two are different.
### Nesting predicates ### Nesting predicates
This returns `<section>` if it has an `<h1>` descendant with `id='hi'`.
``` ```
//section[//h1[@id='hi']] //section[//h1[@id='hi']]
``` ```
This returns `<section>` if it has an `<h1>` descendant with `id='hi'`.
Functions Functions
--------- ---------
### Node functions ### Node functions
```sh ```bash
name() # //[starts-with(name(), 'h')] name() # //[starts-with(name(), 'h')]
text() # //button[text()="Submit"] text() # //button[text()="Submit"]
# //button/text() # //button/text()
lang(str) lang(str)
namespace-uri() namespace-uri()
```
```bash
count() # //table[count(tr)=1] count() # //table[count(tr)=1]
position() # //ol/li[position()=2] position() # //ol/li[position()=2]
``` ```
### Boolean functions ### Boolean functions
```sh ```bash
not(expr) # button[not(starts-with(text(),"Submit"))] not(expr) # button[not(starts-with(text(),"Submit"))]
``` ```
### String functions ### String functions
```sh ```bash
contains() # font[contains(@class,"head")] contains() # font[contains(@class,"head")]
starts-with() # font[starts-with(@class,"head")] starts-with() # font[starts-with(@class,"head")]
ends-with() # font[ends-with(@class,"head")] ends-with() # font[ends-with(@class,"head")]
```
```bash
concat(x,y) concat(x,y)
substring(str, start, len) substring(str, start, len)
substring-before("01/02", "/") #=> 01 substring-before("01/02", "/") #=> 01
@ -246,7 +263,7 @@ string-length()
### Type conversion ### Type conversion
```sh ```bash
string() string()
number() number()
boolean() boolean()
@ -256,58 +273,63 @@ Axes
---- ----
### Using axes ### Using axes
Steps of an expression are separated by `/`, usually used to pick child nodes. That's not always true: you can specify a different "axis" with `::`.
```sh ```bash
//ul/li # ul > li //ul/li # ul > li
//ul/child::li # ul > li (same) //ul/child::li # ul > li (same)
//ul/following-sibling::li # ul ~ li //ul/following-sibling::li # ul ~ li
//ul/descendant-or-self::li # ul li //ul/descendant-or-self::li # ul li
//ul/ancestor-or-self::li # $('ul').closest('li') //ul/ancestor-or-self::li # $('ul').closest('li')
``` ```
{:.light}
Steps of an expression are separated by `/`, usually used to pick child nodes. That's not always true: you can specify a different "axis" with `::`.
| `//` | `ul` | `/child::` | `li` |
| Axis | Step | Axis | Step |
{: .-css-breakdown}
### Child axis ### Child axis
This is the default axis. This makes `//a/b/c` work.
```sh ```bash
# both the same # both the same
//ul/li/a //ul/li/a
//child::ul/child::li/child::a //child::ul/child::li/child::a
``` ```
```sh `child::` is the default axis. This makes `//a/b/c` work.
```bash
# both the same # both the same
# this works because `child::li` is truthy, so the predicate succeeds # this works because `child::li` is truthy, so the predicate succeeds
//ul[li] //ul[li]
//ul[child::li] //ul[child::li]
``` ```
```sh ```bash
# both the same # both the same
//ul[count(li) > 2] //ul[count(li) > 2]
//ul[count(child::li) > 2] //ul[count(child::li) > 2]
``` ```
### Descendant-or-self axis ### Descendant-or-self axis
`//` is short for the `descendant-or-self::` axis.
```sh ```bash
# both the same # both the same
//div//h4 //div//h4
//div/descendant-or-self::h4 //div/descendant-or-self::h4
``` ```
```sh `//` is short for the `descendant-or-self::` axis.
```bash
# both the same # both the same
//ul//[last()] //ul//[last()]
//ul/descendant-or-self::[last()] //ul/descendant-or-self::[last()]
``` ```
### Other axes ### Other axes
There are other axes you can use.
| Axis | Abbrev | Description | | Axis | Abbrev | Notes |
| --- | --- | --- | | --- | --- | --- |
| `ancestor` | | | | `ancestor` | | |
| `ancestor-or-self` | | | | `ancestor-or-self` | | |
@ -325,19 +347,24 @@ There are other axes you can use.
| `following-sibling` | | | | `following-sibling` | | |
| `preceding` | | | | `preceding` | | |
| `preceding-sibling` | | | | `preceding-sibling` | | |
{:.greycode} {: .-headers}
There are other axes you can use.
### Unions ### Unions
Use `|` to join two expressions.
```sh ```bash
//a | //span //a | //span
``` ```
Use `|` to join two expressions.
More examples More examples
------------- -------------
```sh ### Examples
```bash
//* # all elements //* # all elements
count(//*) # count all elements count(//*) # count all elements
(//h1)[1]/text() # text of the first h1 heading (//h1)[1]/text() # text of the first h1 heading
@ -346,28 +373,39 @@ count(//*) # count all elements
//ul/li/.. # use .. to select a parent //ul/li/.. # use .. to select a parent
``` ```
```sh ### Find a parent
# Find a <section> that directly contains h1#section-name
//section[h1[@id='section-name']]
```
```sh ```bash
//section[h1[@id='section-name']]
```
Finds a `<section>` that directly contains `h1#section-name`
```bash
# Find a <section> that contains h1#section-name # Find a <section> that contains h1#section-name
# (Same as above, but use descendant-or-self instead of child) //section[//*[@id='section-name']]
//section[//*[@id='section-name']]
``` ```
```sh Finds a `<section>` that contains `h1#section-name`.
# like jQuery's $().closest('.box') (Same as above, but uses descendant-or-self instead of child)
./ancestor-or-self::[@class="box"]
### Closest
```bash
./ancestor-or-self::[@class="box"]
``` ```
```sh Works like jQuery's `$().closest('.box')`.
# Find <item> and check its attributes
//item[@price > 2*@discount] ### Attributes
```bash
//item[@price > 2*@discount]
``` ```
Finds `<item>` and check its attributes
References References
---------- ----------
{: .-one-column}
* [Xpath test bed](http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm) (whitebeam.org) * [Xpath test bed](http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm) _(whitebeam.org)_