Home >Web Front-end >JS Tutorial >How to Write and Handle Dynamic XPath In Selenium [with Tactics]

How to Write and Handle Dynamic XPath In Selenium [with Tactics]

DDD
DDDOriginal
2024-11-18 06:35:03308browse

How to Write and Handle Dynamic XPath In Selenium [with Tactics]

It is critical for automated testing to be able to recognize the web elements of an Application Under Test (AUT). Learning how to find web elements and writing dynamic XPath in Selenium manually may take a long time and a lot of practice.

For example, we will show you how to manually and easily find web elements in Selenium using XPath.

Locators are one of Selenium’s valuable features. They enable us to locate web elements. For example, if the locators such as id, class name, name, link text, etc., do not find the web elements, we use XPath to find them on the web page.

What Is Dynamic XPath In Selenium?

XPath, also known as XML Path, is one of Selenium WebDriver’s most commonly used locators for navigating through a page’s HTML structure. It can be used to locate any element in a web page using HTML DOM structure in HTML and XML documents.

XPath is intended to allow XML document navigation to select individual elements, attributes, or other parts of an XML document for specific processing. For example, XPath generates reliable locators, but it is slower in terms of performance than CSS Selector.

The language XPath is used to select elements in an HTML page. Using XPath, you can find any element on a page based on its tag name, ID, CSS class, and so on. In Selenium, there are two types of XPath.

Different Approaches to Find Elements using Dynamic XPath in Selenium:

01 Absolute XPath

It is the most direct way to find the element, but the disadvantage of “absolute XPath” is that if the element’s path changes, that particular XPath fails.

The critical feature of XPath is that it begins with a single forward-slash (/), indicating that you can select an element from the root node using Dynamic XPath.

02 Relative XPath

A relative XPath is one in which the path begins at a node of your choice rather than the root node.

The benefit of using relative XPath is that you don’t have to specify the entire XPath; instead, you can begin in the middle or somewhere in between.

*Disadvantages: *

Identifying the element will take longer because we specify a partial path rather than an exact path.

If multiple elements are on the same path, it will choose the first element identified.

How to find XPath for dynamic elements in selenium?

From the context (current) node, the XPath axes search different nodes in the XML document. For example, it is used to find the node closest to that tree.

XPath axes are methods for finding dynamic elements that would be impossible to find using standard XPath methods that do not include an ID, Classname, Name, or other identifiers.

Axes methods are used to locate elements that change dynamically due to a refresh or other operation. For example, child, parent, ancestor, sibling, preceding, self, and other axes methods are commonly used in Selenium Webdriver.

They were modifying test scripts when the AUT changes are one of the most complex and time-consuming tasks in test automation, especially in the early stages of software development.

As a result, developers may frequently change identifiers and elements from one build to another. Furthermore, the AUT’s elements may change dynamically during execution.

To address these issues, automation testers should not set fixed XPaths for test case elements but instead script XPaths dynamically based on specific patterns.

11 Unique Ways to Create Dynamic XPath in Selenium:

Here are the 11 unique and different ways to create dynamic XPath in selenium:

real-device-cloud-cta.jpg

01 Using Single Slash

This mechanism is also known as Absolute XPath element discovery.

Syntax:

html/body/div[1]/div[2]/div[2]/div[1]/form/div[1]/div/div[1]/div/div/input[1]
A single slash is used to create an XPath with an absolute path, i.e., the XPath is designed for beginning selection from the document node/start node/parent node.

02 Using Double Slash

This mechanism is also referred to as finding elements with Relative XPath.

A double slash is used to create an XPath with a relative path, which means that the XPath can begin selection from anywhere in the document. Then, look for the preceding string across the entire page (DOM).

Syntax

//form/div[1]/div/div[1]/div/div/input[1]

03 Utilizing a Single Attribute

The syntax could be written in two ways, as shown below. HTML Tag inclusion or exclusion. If you want to exclude HTML tags, you must use *.

Syntax

//[@attribute_name='attribute_value']
or
//*[@attribute_name='attribute_value']

04 Using Multiple Attributes

Syntax

//[@attribute_name1='attribute_value1'][@attribute_name2='attribute_value2]
or
//*[@attribute_name1='attribute_value1'][@attribute_name2='attribute_value2]

05 Using AND

Syntax

//[@attribute_name1='attribute_value1' and @attribute_name2='attribute_value2]
or
//*[@attribute_name1='attribute_value1' and @attribute_name2='attribute_value2]

06 Using OR

Syntax

//[@attribute_name1='attribute_value1' or @attribute_name2='attribute_value2]
or
//*[@attribute_name1='attribute_value1' or @attribute_name2='attribute_value2]

07 Using contains()

Contains() is a method for identifying an element that changes dynamically and when familiar with some part of the element’s attribute value.

When familiar with the value of an element’s attribute (beginning with the specified text), we can use the starts-with() method to identify it.

syntax

//[contains(@attribute_name,'attribute_value')]
or
//*[contains(@attribute_name,'attribute_value')]

#08 use of text ()

This mechanism is used to find an element based on a web page’s text.

Last() selects the last element (of the specified type) from all input elements.

Syntax

//[text()='New look for sign-in coming soon']
or
//
[text()='New look for sign-in coming soon']

09 Using position(),

The element is chosen from among all input elements based on the position number provided.

In the following XPath, [@type=’text’] will locate a text field, and function [position()=2] will identify a text field in the second position from the top.

Syntax

findElement(By.xpath("(//input[@type='text'])[position()=2]"))
or
findElement(By.xpath("(//input[@type='text'])[2]"))

10 Using an index

We could get to the nth element by putting the index position in square brackets. Then, we were able to identify the Last Name field using the XPath below.

Syntax

findElement(By.xpath("//label[2]"))

11 Using previous XPath axes

Except for ancestors, attribute nodes, and namespace nodes, this selects all nodes that appear before the current node in the document.

How Do I Select A Web element From A List In Selenium?

WebElement select = driver.findElement(By.id(“gender”));
List options = select.findElements(By.tagName(“Male”));
for (WebElement option : options) {
if(“Germany”.equals(option.getText()))
option.click();

How Does Selenium Handle Listbox?

using selectByValue()

Select listbox = new Select(driver.
listbox.
Select listbox = new Select(driver.
WebElement option = listbox.getFirstSelectedOption();
System.out.println(option.getText()); //prints selected option.
//Listing down all the selected options.
//Listing down all the options.

How To Write Dynamic Web Elements In Selenium?

A dynamic element is a Web Element whose IDs and not just IDs, but any attribute such as Class Name, Value, and so on, are not fixed.

Therefore, every time you reload the page, it changes. As a result, you cannot handle that element solely through the locator.

For example, the class name of Gmail Inbox elements changes with each login.

Database-driven or session-driven dynamic elements When you change a database element, it affects several application areas under test.

The dynamic elements are strictly content, with the formatting laid out in the design. Text boxes and buttons are commonly used with dynamic identifiers.

When you automate a dynamic website, the scripts will break as soon as the content changes, causing your test to fail. Then you need to update your test case each time, which is a time-consuming task.

We must always understand how these elements behave when the page is reloaded, or a new session is started. We can prepare a strategy to interact with these elements once we understand them.

#01 Relative Xpath with Starting Text

Similar to the partial link selector in Selenium, we can use Xpath search with the starting Text match element.

#02 Relative Xpath with Node Following or Preceding

All of the nodes that follow the context node are listed below. We can use ‘the following’ to specify the elements listed below in the web element list.

#03 Text Contains Relative Xpath

Few dynamic elements contain static values; based on those values; we can search for such elements using the ‘contains’ function. For example, there is a static string ‘Hstpl-12345’ in the above HTML button class name. For instance, we can use XPath to look for a button element with a class name that includes the word ‘Hstpl.’

#04 Indexed Element

When there are multiple elements in the DOM with similar attributes, it can be challenging to search for them, especially when they are dynamic.

For example, suppose there are ten buttons on a page, and you want to find the fifth one. Then we look for elements with the ‘button’ tag and go to the fifth index of the list of buttons to find that element.

#05 Method of Absolute Xpath

Absolute Xpath uses the entire path from the Root Element to the specific element. As shown below, an absolute Xpath begins with HTML and a forward slash (/). To generate Xpaths, use fire path (firebug).

However, they are more prone to regression because minor changes in the DOM cause them to be incorrect or refer to a different element.

Therefore, using absolute Xpath is not considered best practice in most cases, but it solves the Dynamic element problem.

#06 IWebElement Interface is being used.

Another method for handling dynamic elements is to find all elements with the same Tag name and then search for the required element based on whether it contains text, a value, or element attributes.

Conclusion

This article demonstrated how to use the XPath functions contains(), starts-with(), and text() with attributes and text to uniquely identify elements in the HTML DOM structure.

In Selenium, XPath is used to locate elements when other locators fail. There are two types of Selenium XPath: Absolute XPath and Relative XPath.

Source: This article was originally published at testgrid.io.

The above is the detailed content of How to Write and Handle Dynamic XPath In Selenium [with Tactics]. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn