How to select element with one of many names in XPath?

XPath allows interacting with any element's attribute such as class, id, href and any other through the @ syntax. This means we can select any element in the HTML DOM based on its attribute value with XPath.

To find elements by attribute value, the name of the attribute can be used in [@attribute=value] predicate syntax or using contains() function for a partial match like so: [contains(@attribute, "value")].

Here are some interactive examples to demonstrate this:

  1. We can select the attribute value itself using @ syntax:
<!-- select all links by selecting the @href attributes --> <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>
  1. Or filter elements by attribute value using contains() function:
<!-- select only product links by checking @href attribute --> <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

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.