My automatic test gives the word "MyApplication", it does it very quickly, I need the word to be typed in about 0.5-0.7 seconds. I know I can use time.sleep, but I would like to know another solution, how can I do it differently? I do not want time.sleep, because the query to the server goes only 300 ms and can not be changed. Fast typing causes the test to not work.
yes this is an automatic test. Inscription to input entered by the send keys method.
WebDriverWait(driver, 10).until(
EC.element_to_be_clikable((By.XPATH, "myypath"))
)
driver.find_element(By.XPATH, "myypath").send_keys("MyApplication")
Either introduce a delay which will match the minimum acceptable time that the page can handle:
from selenium import webdriver
import time
def send_delayed_keys(element, text, delay=0.3) :
for c in text :
endtime = time.time() + delay
element.send_keys(c)
time.sleep(endtime - time.time())
driver = webdriver.Chrome()
driver.get("https://www.google.com/search")
element = driver.find_element_by_css_selector('[name="q"]')
send_delayed_keys(element, "abcdef", 0.6)
Or send each key and wait for no pending request:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import time
def send_autocomplete_keys(element, text) :
ajax = AjaxWaiter(element.parent)
for c in text :
element.send_keys(c)
ajax.wait_idle()
driver = webdriver.Chrome()
driver.get("https://www.google.com/search")
element = driver.find_element_by_css_selector('[name="q"]')
send_autocomplete_keys(element, "abcdef")
class AjaxWaiter(object):
JS_IS_XHR_IDLE = """\
if (!('active' in XMLHttpRequest))(function (){
var _send = XMLHttpRequest.prototype.send;
function _onrelease(){ --XMLHttpRequest.active };
function _onloadend(){ setTimeout(_onrelease, 1) };
XMLHttpRequest.active = 0;
XMLHttpRequest.prototype.send = function send() {
++XMLHttpRequest.active;
this.addEventListener('loadend', _onloadend, true);
_send.apply(this, arguments);
};
})();
return XMLHttpRequest.active == 0;
"""
def __init__(self, driver, timeout=10, frequency=0.08) :
self.driver = driver
self.waiter = WebDriverWait(self, timeout, frequency)
self.driver.execute_script(self.JS_IS_XHR_IDLE)
def is_idle(self) :
return self.driver.execute_script(self.JS_IS_XHR_IDLE)
def wait_idle(self) :
self.waiter.until(AjaxWaiter.is_idle, "Pending requests")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With