webdriver wait for ajax request in python
Add this method, where I ensure the API responses are back from server
def wait_for_ajax(driver): wait = WebDriverWait(driver, 15) try: wait.until(lambda driver: driver.execute_script('return jQuery.active') == 0) wait.until(lambda driver: driver.execute_script('return document.readyState') == 'complete') except Exception as e: pass
You indeed can add an explicit wait for the presence of an element like
from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0ff = webdriver.Firefox()ff.get("http://somedomain/url_that_delays_loading")ff.find_element_by_xpath("//div[@class='searchbox']/input").send_keys("obama")try: element = WebDriverWait(ff, 10).until(EC.presence_of_element_located((By.ID, "keywordSuggestion")))finally: ff.find_element_by_xpath("//div[@class='searchbox']/input").send_keys(Keys.RETURN) ff.quit()
See: http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp#explicit-and-implicit-waits
And what about:
driver.implicitly_wait(10)
for your example:
wd.implicitly_wait(10)
In this case every time you are going to click or find element driver will try to do this action every 0.5 second during 10 seconds. In this case you don't need to add wait every time.Note: But it is only about element on screen. It will not wait until some JS actions ends.