方法一
driver.find_element_by__link_text('Next').click()
点击链接后,按钮跳转到新页面,您可以:
等到一些不在旧页面中而是在新页面中的元素出现;
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)
当新页面正在加载(或加载)时,现在您可以通过执行javascript脚本检查其readyState,该脚本将在页面加载时输出“完成”消息(值)。
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.')
这个想法在我的情况下是为我写的,我认为它可以适用于大多数情况,而且很简单。
方法2
从 selenium.common.exceptions 导入 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"]')
这个方法来自'https://blog.codeship.com/get-selenium-to-wait-for-page-load/'(可能从其他地方共享)