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

20,528

Solution 1

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

Solution 2

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()

Share:
20,528
user3587233
Author by

user3587233

Updated on July 09, 2022

Comments

  • user3587233
    user3587233 almost 2 years

    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

  • user3587233
    user3587233 about 10 years
    I tried both of them, but still returns both the elements.
  • helderdarocha
    helderdarocha about 10 years
    Ok. You probably have many nested divs in different contexts. You might need to use additional predicates to better filter your result. Show your code (link to it, and add the relevant parts here). I added parentheses above, which will select only one element, the second in the whole document, but that might not be what you want.