Basic XPath Syntax for Class Selection
To select elements by class in XPath, we use the @class attribute along with the contains() function. Here’s the basic syntax:
//tag[@class='class-name']
Where:
- //tag: Represents the XPath axis selector for all elements of a specific tag type.
- [@class=’class-name’]: Filters elements based on the specified class name.
Examples of Class Selection in XPath:
Let’s consider some examples to illustrate how to select elements by class using XPath:
- Selecting a Div with a Specific Class:
//div[@class='example']
This XPath expression selects all <div> elements with the class attribute set to ‘example’.
- Selecting Elements with Multiple Classes:
//div[contains(@class, 'class1') and contains(@class, 'class2')]
This expression selects elements that have both ‘class1’ and ‘class2’ applied to their class attribute.
- Selecting Elements with Partial Class Matches:
//div[contains(@class, 'partial-class')]
This expression selects elements whose class attribute contains ‘partial-class’, regardless of other classes present.
How to Select Elements by Class in XPath?
XPath (XML Path Language) is a powerful query language used to navigate and select elements in XML and HTML documents. One common task when working with XPath is selecting elements by their class attribute, particularly useful for web scraping and testing scenarios. In this article, we’ll explore how to effectively select elements by class using XPath.