0

I just can't figure this out. It seems I've tried everything, from WebDriverWait, try except statements, driver.implicitly_wait(60) and everything in between.

My code has the following structure:

while True:
    element1 = driver.find_element_by_xpath(xpath1)
    element2 = driver.find_element_by_xpath(xpath2)

    wait = WebDriverWait(driver, 30)
    element1 = wait.until(EC.visibility_of_element_located((By.XPATH, xpath1)))
    element2 = wait.until(EC.visibility_of_element_located((By.XPATH, xpath2)))

    if element1.text == 'some string': # get the exception here
        # do something 
    elif element2.text == 'some string': # or here
        # do something 

    driver.refresh()

I've tried implementing different expected conditions, none work. How can the element become stale between confirming it's visible to calling .text? Is it because the page is still loading? If so, how can I fix this?

SOLUTION: Ok, this seems to be working. If it fails at some point, I'll update this post.

while True:
    try:
        wait = WebDriverWait(driver, 30)
        element1 = wait.until(EC.visibility_of_element_located((By.XPATH, xpath1)))
        element2 = wait.until(EC.visibility_of_element_located((By.XPATH, xpath2)))

        if element1.text == 'some string': # get the exception here
            # do something 
        elif element2.text == 'some string': # or here
            # do something
    except (StaleElementReferenceException, TimeoutException):
        continue

    time.sleep(30)
    driver.refresh() 
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
cap2
  • 53
  • 6
  • Can it help you? You can also implicitly check "if element1 and element1.text == 'some string'". https://stackoverflow.com/questions/27003423/staleelementreferenceexception-on-python-selenium – STerliakov Apr 04 '21 at 10:35
  • I've seen every stack overflow post on this by now haha. No luck. I've even tried `driver.implicitly_wait(60)` – cap2 Apr 04 '21 at 10:36
  • And if you put if's into try-except blocks (each condition separately), than the code doesn't work as you want, right? – STerliakov Apr 04 '21 at 10:39
  • I just tried putting the `if-else` statements into a `try` statement with `continue` in the `except` block. Seems to be working – cap2 Apr 04 '21 at 10:48

0 Answers0