method 1
driver.find_element_by__link_text('Next').click()
After click to a link, button to go to a new page, you can either:
wait until some element which not in the old page but in the new one appeard;
WebDriverWait(driver, 600).until(expected_conditions.presence_of_element_located((By.XPATH, '//div[@id="main_message"]//table')))
# or just wait for a second for browser(driver) to change
driver.implicitly_wait(1)
when new page is loading(or loaded), now you can check on its readyState by execute javascript script, which will output the 'complete' message(value) when page is loaded.
def wait_loading():
wait_time = 0
while driver.execute_script('return document.readyState;') != 'complete' and wait_time < 10:
# Scroll down to bottom to load contents, unnecessary for everyone
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
wait_time += 0.1
time.sleep(0.1)
print('Load Complete.')
This idea worded for me in my case and I think it can suit most cases, and it's easy.
method 2
from selenium.common.exceptions import StaleElementReferenceException
def wait_for(condition_function):
start_time = time.time()
while time.time() < start_time + 10:
if condition_function:
return True
else:
time.sleep(0.1)
raise Exception(
'Time out, waiting for {}'.format(condition_function.__name__)
)
def click_xpath(xpath):
link = driver.find_element_by_xpath(xpath)
link.click()
def link_staled():
try:
link.find_element_by_id('seccode_cSA')
return False
except StaleElementReferenceException:
return True
wait_for(link_staled())
click_xpath('//button[@name="loginsubmit"]')
And this method is from 'https://blog.codeship.com/get-selenium-to-wait-for-page-load/' (may be shared from somewhere else)