<p>找到以下3种方法:</p>
<h3>就绪状态</h3>
<p>正在检查页的readyState(不可靠):</p>
<pre><code>def page_has_loaded(self):
self.log.info("Checking if {} page is loaded.".format(self.driver.current_url))
page_state = self.driver.execute_script('return document.readyState;')
return page_state == 'complete'
</code></pre>
<blockquote>
<p>The <code>wait_for</code> helper function is good, but unfortunately <code>click_through_to_new_page</code> is open to the race condition where we manage to execute the script in the old page, before the browser has started processing the click, and <code>page_has_loaded</code> just returns true straight away.</p>
</blockquote>
<h3><code>id</code></h3>
<p>将新页ID与旧页ID进行比较:</p>
<pre><code>def page_has_loaded_id(self):
self.log.info("Checking if {} page is loaded.".format(self.driver.current_url))
try:
new_page = browser.find_element_by_tag_name('html')
return new_page.id != old_page.id
except NoSuchElementException:
return False
</code></pre>
<blockquote>
<p>It's possible that comparing ids is not as effective as waiting for stale reference exceptions.</p>
</blockquote>
<h3><code>staleness_of</code></h3>
<p>使用<code>staleness_of</code>方法:</p>
<pre><code>@contextlib.contextmanager
def wait_for_page_load(self, timeout=10):
self.log.debug("Waiting for page to load at {}.".format(self.driver.current_url))
old_page = self.find_element_by_tag_name('html')
yield
WebDriverWait(self, timeout).until(staleness_of(old_page))
</code></pre>
<hr/>
<p>有关详细信息,请检查<a href="http://www.obeythetestinggoat.com/how-to-get-selenium-to-wait-for-page-load-after-a-click.html" rel="noreferrer">Harry's blog</a>。</p>