power_settings_new

Can I assign multiple locators to the same element?

by (158 points)
+1 vote
196 views
I have an element that changes the locator under certain conditions. I would like to have one element in my code, but to search for the element in two ways (two locators). I use Selenium.Support classes(C#). Is it possible?

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.

1 Answer

by (171 points)
selected by
+1 vote
 
Best answer

Yes, you can have multiple locators to the same element. But not at the same time. You will have to use if else condition with try catch block.

e.g.

Element ele = null;

try{

ele = driver.findElement(By.id("your id here"));

}catch(NoSuchElementException ignore){

ele = driver.findElement(By.className("your class name here"));

}

 

Hope that helps! Please feel free to comment if you have any questions.

by (158 points)
But how to use this with Selenium.Support classes.
In my code I declare element in this way:

[FindsBy(How = How.XPath, Using = "//div[@class='button']")]
protected IWebElement Button{ get; set; }
by (171 points)
Have you tried simply using FindsBy twice?

[FindsBy(How = How.Id, Using = "myIdhere")]
[FindsBy(How = How.XPath, Using = "//div[@class='button']")]
protected IWebElement Button{ get; set; }
by (158 points)
It works! Thank you!
add
...