How to select elements by attribute value in XPath?

XPath allows interacting with any element's attribute such as class, id, href and any other through the @ syntax.
Attribute values then can be used in predicates using = or contains(). See these interactive examples:

Select attribute value, like the urls of <a> links:

<html> <a href="/categories/1">category</a> <a href="/product/1">product 1</a> <a href="/product/2">product 2</a> <a href="/product/3">product 3</a> </html>

Or filter element based by attribute using contains() function:

<html> <a href="/categories/1">category</a> <a href="/product/1">product 1</a> <a href="/product/2">product 2</a> <a href="/product/3">product 3</a> </html>
Question tagged: XPath

Related Posts

How to Parse XML

In this article, we'll explain about XML parsing. We'll start by defining XML files, their format and how to navigate them for data extraction.

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.