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!

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment