你怎么能降低进入人物硒python的速度

时间:2018-05-02 16:35:05

标签: python selenium selenium-webdriver

我的自动测试给出了单词" MyApplication",它很快就完成了,我需要输入大约0.5-0.7秒的单词。我知道我可以使用time.sleep,但我想知道另一个解决方案,我怎么能以不同的方式做到这一点? 我不想time.sleep,因为对服务器的查询只有300毫秒,无法更改。快速输入会导致测试不起作用。

是的,这是一个自动测试。由发送键方法输入的输入铭文。

WebDriverWait(driver, 10).until(
    EC.element_to_be_clikable((By.XPATH, "myypath"))
)
driver.find_element(By.XPATH, "myypath").send_keys("MyApplication")

1 个答案:

答案 0 :(得分:2)

引入一个延迟,该延迟将与页面可以处理的最短可接受时间相匹配:

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)

或发送每个密钥并等待没有待处理的请求:

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")