Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webdriver click second element in list

Tags:

selenium

The page I'm testing has 2 elements with the same name and I need to click the second Element. I can get the elements by using:

driver.findElements(By.linkText("Services"));

But I don't know how to click on the second element.

like image 661
confusified Avatar asked Feb 04 '14 12:02

confusified


People also ask

How do you select the second element in Selenium?

click();//If there are only two such element, here 1 is index of 2nd element in list returned.

How do you get the second element with the same class name in Selenium?

We can get text from multiple elements with the same class in Selenium webdriver. We have to use find_elements_by_xpath(), find_elements_by_class_name() or find_elements_by_css_selector() method which returns a list of all matching elements.


1 Answers

There are two ways to do this:
1) Using xpath, try in following manner.

driver.findElement(By.xpath("('xpath of the link')[2]"));//If you had given html, I could have added exact xpath.

2) Using findElements() you can try following:

List<WebElement> li = driver.findElements(By.linkText("Services"));;
li.get(1).click();//If there are only two such element, here 1 is index of 2nd element in list returned.

Hope you get the idea. :)

like image 112
Husam Avatar answered Nov 15 '22 23:11

Husam