Selenium WebDriver waitForElementPresent when Javascript refreshes

霸气de小男生 提交于 2019-12-06 11:29:44

问题


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 please :)

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:


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


来源:https://stackoverflow.com/questions/30327602/selenium-webdriver-waitforelementpresent-when-javascript-refreshes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!