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.
-
which language? what code have you already attempted to do so?Tarun Lalwani– Tarun Lalwani2020-06-04 06:27:20 +00:00Commented Jun 4, 2020 at 6:27
-
In JAVA language, looking for the best option that i can useAnkit Choudhary– Ankit Choudhary2020-06-04 06:34:21 +00:00Commented Jun 4, 2020 at 6:34
2 Answers
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.
Comments
Use OR expression for the same. You can pass multiple attribute of the same WebElement.
For example:
Xpath=//*[@type='submit' or @name='btnReset']