How to select sibling elements in XPath?

To select sibling elements in XPath the preceding-sibling and following-sibling axes can be used - see these interactive examples:

  1. preceding-sibling::span will select any siblings that precede (i.e. are above) the current element:
<!-- we can find tax rate by navigating from price--> <div> <article> <h1>title</h1> <p>paragraph</p> <span>(no tax)</span> <h3>2.99</h3> </article> </div>
  1. following-sibling::span will select siblings that follow (i.e. are below) the current element:
<!-- we can find currency by navigating from price--> <div> <article> <h1>title</h1> <p>paragraph</p> <p>paragraph with <a href="/foo.html">link</a></p> <span>(no tax)</span> <h3>2.99</h3> <span>USD</span> </article> </div>

Note that the wildcard character can be used instead of explicit element names (e.g. following-sibling::*) to select siblings of any element name.

For more on XPath, see our full introduction article

Question tagged: XPath

Related Posts

Ultimate XPath Cheatsheet for HTML Parsing in Web Scraping

Ultimate companion for HTML parsing using XPath selectors. This cheatsheet contains all syntax explanations with interactive examples.

Web Scraping With Ruby

Introduction to web scraping with Ruby. How to handle http connections, parse html files for data, best practices, tips and an example project.

Parsing HTML with Xpath

Introduction to xpath in the context of web-scraping. How to extract data from HTML documents using xpath, best practices and available tools.