How to use WebDriverWait with a str variable By.XPATH

437 views Asked by At

I'm having trouble finding how to implement the implicit wait when I have a string variable in the xpath.

I'm currently using a 10 second explicit wait before getting to this snippet and it works good, but I don't want to wait 10 seconds if I don't have to (it's usually around 6 seconds to load)

try:
    link = driver.find_element_by_xpath("//tr[@data-recordindex = '"+str(i)+"']//img[contains(@class,'x-tree-expander')]")
    datarow = driver.find_element_by_xpath("//tr[@data-recordindex = '"+str(i)+"']")
    print("Level: " +str(level)+ ": " +datarow.text)
    link.click()
except NoSuchElementException:
    not_a_point = False

I've tried this and it's not waiting, just taking the next link and not the one I'm waiting on to appear. I'm assuming I can't just put the same thing in By.XPATH as I put in find_element_by_xpath().

try:
    link = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//tr[@data-recordindex = '"+str(i)+"']//img[contains(@class,'x-tree-expander')]")))
    datarow = driver.find_element_by_xpath("//tr[@data-recordindex = '"+str(i)+"']")
    print("Level: " +str(level)+ ": " +datarow.text)
    link.click()
except NoSuchElementException:
    not_a_point = False
1

There are 1 answers

0
undetected Selenium On

You need to take care of a couple of things as follows:

  • ImplicitWait isn't that effective when dealing with dynamic elements/websites and you need to induce WebDriverWait.
  • 10 seconds or 6 seconds the timespan for Explicit Wait must be implemented as per the Test Design Docs.
  • As I answered to your previous question to locate the element you need to induce WebDriverWait for the visibility_of_element_located() and you can use the following Locator Strategy:
    • Using variable:

      link = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//tr[@data-recordindex = '" + str(i) + "']//img[contains(@class,'x-tree-expander')]")))
      
    • Using %s:

      link = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//tr[@data-recordindex = '%s']//img[contains(@class,'x-tree-expander')]"% str(i))))
      
    • Using {}:

      link = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//tr[@data-recordindex = '{}']//img[contains(@class,'x-tree-expander')]".format(str(i)))))
      

References

You can find a couple of relevant detailed discussions on how to deal with variables within in: