2

I have a Selenium script (Python) using WebDriver that does

WebDriverWait(driver, long_wait).until(
    EC.presence_of_element_located(find_element(driver, selector))
)

However the page the script is "waiting" for the element to appear on is using Javascript to refresh itself. The page refreshes itself every second and a "success" element will appear after a few refreshes. It appears upon refresh the above command exits however I want it to wait indefinitely (or for a long period) even across client/browser refreshing.

Is this possible with WebDriver?

Edit: Here's the body of the method. Ignore my debugging hacks :)

def waitForElementPresent(self, driver, selector):
    try:
        WebDriverWait(driver, 10, ignored_exceptions=[
            NoSuchElementException, StaleElementReferenceException
        ]).until(EC.presence_of_element_located(find_element(driver,     selector)))
    except NoSuchElementException:
        print("No such element, waititng again")
        self.waitForElementPresent(driver, selector)

    print("Returning normally")
    return

The finally is reached on the first javascript refresh on the client.

1 Answer 1

2

Just wait for the element to be present in a usual way, the recursive approach and special exception handling are not needed here:

def waitForElementPresent(driver, selector):
    return WebDriverWait(driver, 60).until(EC.presence_of_element_located(selector))

element = waitForElementPresent(driver, (By.ID, "myid"))
Sign up to request clarification or add additional context in comments.

7 Comments

NoSuchElementException is ignored by default iirc, however even using the ignored exception code I still get NoSuchElementException when wrapping the call in a try ... puzzling. I suppose I could always loop on that, but that seems a bit grim given the wait API's purpose/design
@AidenBell correct, NoSuchElementException is added by default, just wanted to be explicit. Could you please share the code you are executing now (the relevant part at least; at most, the complete code if this is a public site and I can reproduce the issue too)? Thank you!
I added the function body being used
Actually, I think it might be working now ... something odd is going on
@AidenBell I've updated the answer and added what worked for me on this sample page.
|

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.