Here's an example to wait for no pending Ajax request with Chrome:
from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support.ui import WebDriverWait
import json
def send_chrome(driver, cmd, params={}) :
resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id
url = driver.command_executor._url + resource
body = json.dumps({'cmd': cmd, 'params': params})
response = driver.command_executor._request('POST', url, body)
if response.get('status'):
raise Exception(response.get('value'))
return response.get('value')
def extend_xhr_chrome(driver) :
send_chrome(driver, "Page.addScriptToEvaluateOnNewDocument", {
"source":
"(function(){"
" var send = XMLHttpRequest.prototype.send;"
" var release = function(){ --XMLHttpRequest.active };"
" var onloadend = function(){ setTimeout(release, 1) };"
" XMLHttpRequest.active = 0;"
" XMLHttpRequest.prototype.send = function() {"
" ++XMLHttpRequest.active;"
" this.addEventListener('loadend', onloadend, true);"
" send.apply(this, arguments);"
" };"
"})();"
})
def is_xhr_idle_chrome(driver) :
return send_chrome(driver, 'Runtime.evaluate', {
'returnByValue': True,
'expression': "XMLHttpRequest.active == 0"
})['result']['value']
# launch Chrome
driver = webdriver.Chrome()
# extend XMLHttpRequest
extend_xhr_chrome(driver)
driver.get("https://stackoverflow.com")
# wait for no pending request
WebDriverWait(driver, 20, 0.08)
.until(is_xhr_idle_chrome)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…