0

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.

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

2 Answers2

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 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:

  1. "//div[contains(@class, 'copyable-text')]"
  2. "//div[contains(@class, 'copyable-text') and @data-tab='1']"
  3. "//div[contains(@class, 'copyable-text') and @data-tab='1'][@dir='ltr']
  4. "//div[contains(@class, 'copyable-text') and @data-tab='1'][@dir='ltr' and @spellcheck='true']"
  5. "//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