繁体   English   中英

在Java上的get()之前在Selenium WebDriver上执行javaScript

[英]execute javaScript on Selenium WebDriver before get() on java

我正在尝试使用Java中的硒访问网页。 问题是该站点Exception in thread "main" org.openqa.selenium.WebDriverException: com.gargoylesoftware.htmlunit.ScriptException: ReferenceError: "require" is not defined.给我一个错误Exception in thread "main" org.openqa.selenium.WebDriverException: com.gargoylesoftware.htmlunit.ScriptException: ReferenceError: "require" is not defined.
我问了一个前端开发人员,并告诉我应该在加载页面之前尝试加载JavaScript。 他提到的脚本是require.js ,我在https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js中找到了它

我正在使用htmlunit-driver 2.28我注意到在初始化驱动程序时
HtmlUnitDriver driver =new HtmlUnitDriver(true);
我确实有选择
driver.executeScript(script, args)
WebDriver driver =new HtmlUnitDriver(true);上不可用
我想我可以解决它(因为我的代码正在使用WebDriver在其他项目上生产)并使用HtmlUnitDriver,但是我不知道如何使用executeScript来传递脚本的url。

如何将其注入WebDriver? 谢谢

您必须自定义HtmlUnitDriver使用的WebClient。 默认情况下,throwExceptionOnScriptError选项为true。 但是,如果发生(未处理的)异常,则所有浏览器都将忽略对Javascrip的处理。 如果我说对了,那么如果使用真正的浏览器运行,您的页面也会抛出该异常; 意味着你必须

  1. 抛出throwExceptionOnScriptError
  2. 与page / js开发人员讨论代码质量

样例代码:

WebDriver driver = new HtmlUnitDriver(true) {
    @Override
    protected WebClient modifyWebClient(WebClient client) {
        client.getOptions().setThrowExceptionOnScriptError(false);
        return client;
    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM