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
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.
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.
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.
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.
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With