How to select elements by ID in XPath?

To select elements by element ID using XPath we can match the @id attribute using the = operator or the contains() function.

For example, to select <a id="home"></a> element we could use //a[@id="home"] or //a[contains(@id, "home")] selectors. See these interactive examples:

<html> <a id="ignore"></a> <a id="home">website</a> <a id="ignore2">website 2</a> </html>

For dynamic IDs we can use contains() to match elements by partial ID:

<html> <a id="ignore"></a> <a id="home-231">website</a> <a id="ignore2">website 2</a> </html>
Question tagged: XPath

Related Posts

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.

Web Scraping With PHP 101

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