【问题标题】:selenium webdriver - enabling javascript takes too much time to navigate to URLselenium webdriver - 启用 javascript 需要太多时间来导航到 URL
【发布时间】:2018-05-23 06:18:55
【问题描述】:

我正在使用 Selenium Web 驱动程序导航到一个页面。我正在使用 HtmlUnitDriver 进行无头测试(没有 GUI)。这是我的简单代码:

/*
 * Create web driver object
 */
WebDriver webDriver = new HtmlUnitDriver(){
        //@override
        protected WebClient getWebClient() {
            WebClient webClient = super.getWebClient();
            //webClient.getCache().setMaxSize(0);
            //webClient.getOptions().setUseInsecureSSL(true); //ignore ssl certificate
            webClient.getOptions().setThrowExceptionOnScriptError(false);
            webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
            webClient.getOptions().setPrintContentOnFailingStatusCode(false);
            webClient.getOptions().setJavaScriptEnabled(true);
            webClient.getOptions().setCssEnabled(true);
            webClient.setCssErrorHandler(new SilentCssErrorHandler());
            webClient.getOptions().setRedirectEnabled(true);
            //webClient.getOptions().setTimeout(10000);
            return webClient;
        }
    };

现在我正在导航到一个页面 - http://google.com

long startTime = System.currentTimeMillis();
webDriver.get("http://google.com");
long timeTaken = System.currentTimeMillis() - startTime;
System.out.println(Thread.currentThread().getName()+" Result:: Title: "+webDriver.getTitle()+" Current URL: "+webDriver.getCurrentUrl()+" Time taken(ms): "+timeTaken);

我发现导航到上述网址所花费的时间约为 3 秒

如果 JavaScript 被禁用为 webClient.getOptions().setJavaScriptEnabled(false);,则大约需要 ~1 秒

在启用了 javascript 的浏览器上,当我导航到 http://google.com 而没有任何先前的缓存时,大约需要 1 秒。

现在我的问题是为什么在代码中启用 javascript 需要额外的时间,以及我需要做哪些代码更改来消除保持启用 javascript 的额外时间。这也发生在其他网站上。

任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: java selenium selenium-webdriver webdriver htmlunit


    【解决方案1】:

    如果启用了 javascript,HtmlUnit 将像每个浏览器一样处理页面上的所有 javascript。而这需要时间。至少在处理大量 javascript 的页面上,作为现代浏览器,处理速度可能会更慢。

    禁用 javascript 可能会导致页面无法(完全)工作,因为那里的所有网页设计师/开发人员都认为 Javascript 在每个浏览器中都可用,并且所有花哨的效果(以及所有用户跟踪)都是使用 javascript 完成的。

    【讨论】:

    • 我同意。但是处理时间应该没有太大差异。如果一个实际的浏览器加载大约需要 1-2 秒,那么 selenium web 驱动程序也应该花费类似的时间。如果您使用其他站点,例如ndtv.com,您会看到时间差异约为 20-30 秒(实际浏览器需要 15 秒,而 selenium Web 驱动程序需要 45 秒)
    • 是的,更好的性能总是一件好事。如果您有时间,欢迎您分析 javascript 执行并提供补丁以使 javascript 引擎更快。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多