3
el = driver.find_elements_by_xpath("//div[contains(@class,'statsprogramsgridmodal')]//div[contains(@class,'ui-grid-icon-ok')]")

I have written above xpath to find the web element. It gives me three result. I want to click on second web element. Could you please tell me how it can be done in python selenium?

2
  • Which second element? Sibling? Can you give us an html example please. Commented Oct 6, 2017 at 10:13
  • That is not sibling, all three are at same lavel Commented Oct 6, 2017 at 10:19

2 Answers 2

9

with an xpath returning the 2nd match from all results :

el = driver.find_element_by_xpath(
  "(//div[contains(@class,'statsprogramsgridmodal')]//div[contains(@class,'ui-grid-icon-ok')])[2]")

with an xpath returning the 2nd child from the same level :

el = driver.find_element_by_xpath(
  "//div[contains(@class,'statsprogramsgridmodal')]//div[contains(@class,'ui-grid-icon-ok')][2]")

or with an xpath returning multiple elements:

el = driver.find_elements_by_xpath(
  "//div[contains(@class,'statsprogramsgridmodal')]//div[contains(@class,'ui-grid-icon-ok')]")[1]

or with a css selector returning multiple elements:

el = driver.find_elements_by_css_selector(
  "div[class*='statsprogramsgridmodal'] div[class*='ui-grid-icon-ok']")[1]
Sign up to request clarification or add additional context in comments.

3 Comments

Your first solution did work for me. Only problem is index numbering. For my case if I set [2] index after xpath, it selects the 3rd element and [1] select the second element and [0] index select the first one. You just change it, I will accept your answer
@Shoaib Akhtar, an XPath takes a base 1 index and the command returns a base 0 array. Could you check it again. Be aware that (//xxx/xxx)[2] returns the second result while //xxx/xxx[2] returns the 2nd child.
Thanks for the explanation. I was not putting the xpath in braces driver.find_element_by_xpath("(//xxx/xxx)[2]"). Your solution is working well. Thanks
0

you can try:

driver.find_element_by_xpath('//yourXpath/following-sibling::node()').click()

or

driver.find_element_by_xpath('//yourXpath/following-sibling::theTag').click()

Where the theTag is whatever you want: div, tr, ul, ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.