How to Select Elements by Class in XPath?
Last Updated :
17 May, 2024
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.
Understanding XPath and Class Attributes:
XPath operates by traversing the hierarchical structure of XML or HTML documents, allowing precise selection of elements based on various criteria, such as element names, attributes, and their relationships. Class attributes are commonly used in HTML to apply CSS styles and group elements with similar characteristics.
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.
XPath Absolute XPath:
Absolute XPath expressions provide the complete path from the root element to the desired element in the XML or HTML document. They start with a single forward slash /, denoting the root node, and then traverse down the hierarchy to reach the target element.
Example:
/html/body/div[1]/p[2]/a
This Absolute XPath specifies the exact path to the second <a> element within the first <div> inside the second <p> tag within the <body> tag within the <html> tag.
Relative XPath:
Relative XPath expressions, on the other hand, specify the path relative to a reference node or context node. They do not start from the root element but rather from any desired node within the document. Relative XPath expressions typically begin with a double forward slash //, which instructs XPath to search the entire document for the specified element.
Example:
//div[@class='example']/p/a
This Relative XPath selects all <a> elements within <p> tags that are descendants of <div> elements with the class attribute set to 'example'. It searches the entire document for matching elements, regardless of their position.
When to Use Each Type:
- Absolute XPath: Use Absolute XPath when the structure of the document is unlikely to change, and you need an exact, specific path to the element. However, Absolute XPath expressions can become brittle if the structure of the document changes, requiring frequent updates.
- Relative XPath: Relative XPath is more flexible and resilient to changes in the document structure. Use Relative XPath when the exact location of the element is less critical, or when you need to target elements based on their attributes, relationships, or content rather than their exact position in the document hierarchy.
Example: Below we have written basic html code to find the xpath.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<h1 class="title">Welcome to my website</h1>
<p class="content">This is a paragraph.</p>
<p class="content">Another paragraph.</p>
</div>
</body>
</html>
Steps For Finding Xpath:
Step 1: First we will open the inspect we can use shortcut for that ctrl+shift+i.
Step 2: Now we will select the element for that we need to find xpath, now right click on that element we will get the option copy.
Step 3: choose the click on the copy then we will get options to copy the Xpath.
Step 4: Now to verify that we have copied corrcet xpath we press ctrl+f and then paste that xpath after doing this element got highlighted that show's we have copied correct xpath.
Syntax:
XPath for H1 tag and all P tag:
//h1[@class='title'] | //p
Output:
Similar Reads
How to Select the Next Element in CSS ? Combinators: When classes are combined, they become more specific. This allows you to target classes further down in your template without affecting other elements. Selectors can be combined into a combinator: Combinator of Descendent, Child, Sibling, and General Sibling. The Descendent Combinator i
3 min read
How To Get Element By Class Name In JavaScript ? When working with the DOM in JavaScript, selecting elements by their class names is a common task. JavaScript provides several methods to achieve this, whether we need to select one or multiple elements. In this article, we will cover different approaches to get elements by class name in JavaScript.
3 min read
How to select an element by its class name in AngularJS? Given an HTML document and the task is to select an element by its className using AngularJS. The elements can be selected with the help of a class name using the document.querySelector() method that is used to return the first element that matches a specified CSS selector(s) in the document. Approa
2 min read
How to select elements by data attribute using CSS? CSS provides a way to select HTML elements based on attributes and their values. This can be extremely helpful for targeting elements in a flexible and specific way. This enables fine-tuned control over styling elements in a webpage.Here are the different ways to select elements using attribute sele
2 min read
How to Get Child Element in Selenium? The tool that reduces human effort and makes the work relatively easier by automating the browser is known as Selenium. The elements which are located within some other elements, such elements are called child elements. Sometimes, we have to handle such elements, such as values of radio buttons, lis
5 min read
How to select elements by attribute in jQuery ? jQuery is a lightweight JavaScript library. In the vanilla JavaScript language, the getElementById method is used to select an element. However, jQuery provides a much lighter alternative for the same purpose. The 'jQuery Selector' allows the user to manipulate HTML elements and the data inside it(D
2 min read