Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

So basically I'm trying to design a generic method using selenium, that waits for all the background network calls to finish (Including any Ajax, Angular, API calls). I know there is a way to get number of active ajax using JQuery.active, but that works only when the application is build upon JQuery framework. Moreover, i want something that waits for all the network calls to finish and not something specific to Ajax alone.

So here i'm trying to get the number of network calls that are happening currently in the background and wait for it to be zero.

However, that's my idea of handling it, any new ideas or suggestions are welcomed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
355 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...