0

I want to let Selenium wait until a particular text is present in an element. I know the XPath of the element:

driver.find_elements(By.XPATH, ".//*[@class='sr-match-default__darts-leg']")

The above returns a list of 5 WebElements. My focus is on the 4th element. How do I add an index to the XPath-address? The goal is to insert the desired XPath-reference into the code below:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 300)
wait.until(EC.text_to_be_present_in_element((By.XPATH, ".//*[@class='sr-match-default__darts-leg']"), "Leg 1"))

Please advice. Thank you

HJA24
  • 410
  • 2
  • 11
  • 33
  • Does this answer your question? [How to select specified node within Xpath node sets by index with Selenium?](https://stackoverflow.com/questions/3674569/how-to-select-specified-node-within-xpath-node-sets-by-index-with-selenium) – JaSON Mar 18 '22 at 18:37

1 Answers1

2

You can wrap the xpath inside () and put index 4 like this:

(.//*[@class='sr-match-default__darts-leg'])[4]

Note that since we've given the index, it should ideally return a single webelement.

It is advised to use

  1. driver.find_element(By.XPATH, "(.//*[@class='sr-match-default__darts-leg'])[4]") not elements

  2. WebDriverWait(driver, 30).until(EC.text_to_be_present_in_element((By.XPATH, "(.//*[@class='sr-match-default__darts-leg'])[4]", "Leg 1"))

cruisepandey
  • 28,520
  • 6
  • 20
  • 38
  • great, thank you. And Xpath-indexing starts at 1 right? – HJA24 Mar 18 '22 at 14:55
  • yes it starts from 1 – cruisepandey Mar 18 '22 at 14:58
  • @cruisepandey Ironically [if the UI dev adds one more td in between, then td12 would not work](https://stackoverflow.com/questions/71497122/locating-element-in-the-dom-with-parent-selenium-xpath/71497244#comment126369632_71497244) and you still suggest _**put index 4 like this**_ – undetected Selenium Mar 18 '22 at 21:47
  • @undetectedSelenium: if you read it carefully, here ask is `How do I add an index to the XPath-address?` OP is looking for an `index-based xpath`. Now if you ask me honestly, I'd still say avoid index as much as possible cause index-based locators are always brittle in nature. Don't be surprised to see my comment on answers where they could eliminate the possibility of having indexation however they haven't. – cruisepandey Mar 19 '22 at 05:40
  • @cruisepandey Let's cut off all the noise, it's either of, either you use index or you avoid index. But it's unethical to critisize other's answers based on index and at the same time suggest usage of index in your own answers. – undetected Selenium Mar 19 '22 at 06:23