Home > other >  How to check for text_to_be_present_in_xth_element with Selenium
How to check for text_to_be_present_in_xth_element with Selenium

Time:03-20

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

CodePudding user response:

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

  • Related