How to handle multiple xpath for same locator using Selenium, i.e if one is failed use another locator for same field before failing script.
Asked
Active
Viewed 3,195 times
0

undetected Selenium
- 183,867
- 41
- 278
- 352

Ankit Choudhary
- 73
- 3
- 8
-
which language? what code have you already attempted to do so? – Tarun Lalwani Jun 04 '20 at 06:27
-
In JAVA language, looking for the best option that i can use – Ankit Choudhary Jun 04 '20 at 06:34
2 Answers
1
To start with each WebElement within the DOM Tree can be uniquely identified using any of the available Locator Strategies.
However, you can construct multiple xpath for the same element using permutation and combination of the available attributes and their values. As an example, for the element below:
<div class="_2S1VP copyable-text selectable-text" data-tab="1" dir="ltr" spellcheck="true" contenteditable="true"></div>
You can construct multiple xpaths as follows:
"//div[contains(@class, 'copyable-text')]"
"//div[contains(@class, 'copyable-text') and @data-tab='1']"
"//div[contains(@class, 'copyable-text') and @data-tab='1'][@dir='ltr']
"//div[contains(@class, 'copyable-text') and @data-tab='1'][@dir='ltr' and @spellcheck='true']"
"//div[contains(@class, 'copyable-text') and @data-tab='1'][@contenteditable='true']"
All these xpaths would identify the same element. But what matters most is the xpath should be able to identify the desired element uniquely. The responsibility of constructing the optimized xpath is solely on the test creator.

undetected Selenium
- 183,867
- 41
- 278
- 352
0
Use OR
expression for the same. You can pass multiple attribute of the same WebElement
.
For example:
Xpath=//*[@type='submit' or @name='btnReset']

frianH
- 7,295
- 6
- 20
- 45

Manisha Singh
- 35
- 4