当前位置: 首页 > 知识库问答 >
问题:

理解在Selenium中执行异步脚本

施海
2023-03-14
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
var div = element(by.css('div.table-scroll'));
var lastRow = element(by.css('table#myid tr:last-of-type'));

browser.executeScript("return arguments[0].offsetTop;", lastRow.getWebElement()).then(function (offset) {
    browser.executeScript('arguments[0].scrollTop = arguments[1];', div.getWebElement(), offset).then(function() {
        // assertions

    });
});
driver.execute_script('var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', element)

它涵盖了哪些用例?何时应该使用execute_async_script()而不是常规的execute_script()

这个问题与硒有关,但与语言无关。

共有1个答案

佴阳曦
2023-03-14

何时应该使用execute_async_script()而不是常规的execute_script()

在浏览器端检查条件时,可以使用execute_async_script执行的所有检查都可以使用execute_script执行。即使您正在检查的内容是异步的。我知道,因为很久以前execute_async_script有一个bug,如果脚本返回结果太快,我的测试就会失败。就我所知,这个bug现在已经消失了,所以我一直使用execute_async_script,但在此之前的几个月里,我使用execute_script执行任务,而execute_async_script会更自然。例如,执行一个检查,需要用RequireJS加载一个模块来执行检查:

driver.execute_script("""
// Reset in case it's been used already.
window.__selenium_test_check = undefined;
require(["foo"], function (foo) {
    window.__selenium_test_check = foo.computeSomething();
});
""")

result = driver.wait(lambda driver: 
    driver.execute_script("return window.__selenium_test_check;"))

require调用是异步的。不过,除了将变量泄漏到全局空间之外,这样做的问题是它会成倍增加网络请求。每个execute_script调用都是一个网络请求。wait方法通过轮询工作:它运行测试,直到返回的值为true。这意味着wait执行的每个检查需要一个网络请求(在上面的代码中)。

result = driver.execute_async_script("""
var done = arguments[0];
require(["foo"], function (foo) {
    done(foo.computeSomething());
});
""")
 类似资料:
  • 问题内容: 我已经使用了很长一段时间了(使用python绑定以及大多数情况下),每次我需要执行javascript代码时,我都使用过method。例如,用于滚动页面(python): 或者,要在另一个元素(量角器)内无限滚动: 或者,为了获取所有元素属性的字典)(python): 但是,WebDriver API也具有我个人未使用过的功能。 它涵盖了哪些用例?什么时候应该代替常规? 这个问题是se

  • 异步注解@Async,默认情况下是不生效的,需要的话可以启用. 该加载器有一个可选参数,线程池大小,默认是32,详情可以查阅org.nutz.aop.interceptor.async.AsyncAopIocLoader @IocBy( args={"*json","ioc/", "*anno","net.wendal.nutzbook", "*a

  • Node 库以多种方式处理异步功能。最常见的模式是 error-first callbacks,但是你还可能会遇到 streams、promises、event emitters、child processes, 或 observables。gulp 任务(task)规范化了所有这些类型的异步功能。 任务(task)完成通知 当从任务(task)中返回 stream、promise、event e

  • 好心的,谁能帮助关于以下例外的根本原因。 test_automation.tc_invoice_printing.tc_input_fields_validation(tc_invoice_printing.java:37)在java.base/jdk.internal.reflect.nativeMethodAccessorImpl.Invoke0(本机方法)在java.base/jdk.int

  • 如果我像下面这样使用forloop- 它只对Row的最后一个值执行driver.findElement命令。如果我在这个for循环中放入第一个return语句(如上),它只对row=2执行并关闭浏览器。

  • 其中test.py为: 我为python、geckdodriver和firefox授予了整个lib目录的权限,以便在IIS_IUSRS(使用Windows)下进行完全控制。 Geckodriver的日志: 产生错误: 文件“C:\inetpub\wwwroot\jobdescription\test.py”,第13行,在driver=webdriver.firefox(firefox_option