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

Provided by Scrapfly

This knowledgebase is provided by Scrapfly — a web scraping API that allows you to scrape any website without getting blocked and implements a dozens of other web scraping conveniences. Check us out 👇