Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the second element that has the same class name in selenium

I have a 2 elements on my web page that has the same class name and I am trying to access the second element and I am unable to do that. I tried [position=1] and by putting [1] at the end of my xpath expression

driver.find_element_by_xpath("//div[@class='tableType value']")

the above returns the following 2 elements

I tried

driver.find_element_by_xpath("//div[@class='tableType value']")[1]
driver.find_element_by_xpath("//div[@class='tableType value'][position=1]")

Can someone please help me with this?

Thank you

like image 933
user3587233 Avatar asked May 23 '14 00:05

user3587233


People also ask

How do you find all elements with the same class 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.

Where is the second element in Selenium?

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.

How do you get sibling elements in Selenium?

We can find a next sibling element from the same parent in Selenium webdriver. This is achieved with the help of xpath locator. It is important to note that it is only possible to traverse from current sibling to the next sibling with the help of xpath.

How can Selenium select each div separately that have the same class?

We can select each div separately that have the same class with the help of the Selenium webdriver. Often in the html code, we find more than one div element having a class attribute with the same value.


2 Answers

Use

driver.find_element_by_xpath("(//div[@class='tableType value'])[2]")

or

driver.find_element_by_xpath("(//div[@class='tableType value'])[position()=2]")

XPath starts counting at 1, so the second element is at position() 2

like image 88
helderdarocha Avatar answered Oct 07 '22 07:10

helderdarocha


Hi please find the below code to click on the second element having the same class names. [1] means if you would like to click on second, [2] means if you would like to click on third....

driver.find_elements_by_class_name('classname')[1].click()

like image 21
Vani Avatar answered Oct 07 '22 06:10

Vani