🚀 We are hiring! See open positions

How to select elements by ID in XPath?

by Bernardas Alisauskas Dec 26, 2023 1 min read

To select elements by element ID using XPath we can match the @id attribute with 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 as seen in 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>

Note that by CSS design there should only be one element of a given ID on the page which makes selecting elements by ID a very fast and reliable method.

Scale Your Web Scraping
Anti-bot bypass, browser rendering, and rotating proxies — all in one API. Start with 1,000 free credits.
No credit card required 1,000 free API credits Anti-bot bypass included
Not ready? Get our newsletter instead.