Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I distinguish between two elements having same ids on same page using Selenium Webdriver?

I have two lists on my web page and both of them have button (image) to select all the items from the list. Both images have the same id and don't have any other information like class name, CSS, XPath. I want to click on the second image to select all the items from the second list. But when the web driver executes the following line:

driver.findElement(By.id("MoveAllRight")).click();

It always clicks on the first image, but I want it to click on the second one.

Can anybody help me for this?

like image 526
VipSha Avatar asked Nov 30 '22 13:11

VipSha


2 Answers

Don't. Instead, raise a bug. It's invalid HTML.

If you really want to continue testing something that is invalid, and you also want to corrupt your automated tests (which you really don't want to do), you could do the following:

driver.findElement(By.xpath("(//img[@id='MoveAllRight'])[2]")).click();

It will work, but it is the wrong thing to do.

like image 100
Ardesco Avatar answered Dec 09 '22 17:12

Ardesco


It always clicks the first one because findElement will return the first one found matching your criteria. You could use findElements to return a list of all the elements that match, then access the second one found. You could also use a xpath such as //img[@id='MoveAllRight'][2].

One thing you might want to do is investigate if you could create an xpath that would take into account the drop down it should be associated with this way you can ensure that the image you are clicking is always the image for that particular dropdown. Difficulty of this depends on your application.

like image 36
Greg A. Avatar answered Dec 09 '22 18:12

Greg A.