xpath tutorial


Author: yifei / Created: May 30, 2017, 10:47 a.m. / Modified: May 30, 2017, 10:55 a.m. / Edit

Yifei's Notes

xpath is the single most powerful xml/html manipulator I have ever found

http://ipointer.cnblogs.com/archive/2005/10/20/258305.html

xpath counts starts from 1

Xpath 101 ( http://plasmasturm.org/log/xpath101/ )

"/": means steps "[]": means predicates "::": axes specify which set of nodes to select before checking conditions

example

And then /foo[bar] means this:

  1. Start with the root node.
  2. Then /foo: for each node, fetch its child nodes, check which ones are foo elements, and take those as the new set.
  3. Then [bar]: for each node, fetch its child nodes, check if any are bar elements, and if you come up empty then discard that node.

basic syntax

syntax
[.]/tag?attr?/tag[x]/tag.../func() select elements
/@id select attributes

/ or // is the seperator

[] can have @attr, index, tagname

./tag is equal to tag

functions

function explain
not()
last()
count() count child element
normalize-space
name()
position() return the postion(), like last()

axis

axis explain
/child::tag default axis
/parent::tag parent axis
/descendant(-or-self)::tag equals to //
/ancestor::tag
/following-sibling::tag
/preceding-sibling::tag
/following::tag all tag after the element
/preceding::tag
/self::tag
*sepeator * explain
/ select elements, direct decendants
// select elements, all decendants
/TAG top level tag elements
//tag all tag elements
* wildcard for all tags or all elements
/* all top level elements
. current element, other wise starts from root

cookbook

problem recipe
contains text //*[text()[contains(.,'ABC')]]
has class //*[contains(concat(' ', normalize-space(@class), ' '), ' className ')]

use in chrome devtools

$x(xpath_expr)

use in javascript

document.evaluate


评论区