[英]execute javaScript on Selenium WebDriver before get() on java
I am trying to access a web page using selenium in Java. 我正在尝试使用Java中的硒访问网页。 The problem is that the site is giving me an error 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.
给我一个错误Exception in thread "main" org.openqa.selenium.WebDriverException: com.gargoylesoftware.htmlunit.ScriptException: ReferenceError: "require" is not defined.
I asked a front end dev and told me that i should try to load a javascript before the loading of the page. 我问了一个前端开发人员,并告诉我应该在加载页面之前尝试加载JavaScript。 The script he mentioned is require.js
and i found it at https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js 他提到的脚本是require.js
,我在https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js中找到了它
I am using htmlunit-driver 2.28
I noticed that when I initialise the driver like 我正在使用htmlunit-driver 2.28
我注意到在初始化驱动程序时
HtmlUnitDriver driver =new HtmlUnitDriver(true);
I do get an option of 我确实有选择
driver.executeScript(script, args)
which is not available on WebDriver driver =new HtmlUnitDriver(true);
WebDriver driver =new HtmlUnitDriver(true);
上不可用
I guess i can work around it (since my code is on production for other projects using WebDriver) and use HtmlUnitDriver but I have no idea how to use the executeScript to pass a url for the script 我想我可以解决它(因为我的代码正在使用WebDriver在其他项目上生产)并使用HtmlUnitDriver,但是我不知道如何使用executeScript来传递脚本的url。
How can I inject this to my WebDriver? 如何将其注入WebDriver? Thanks 谢谢
You have to customize the WebClient used by the HtmlUnitDriver a bit. 您必须自定义HtmlUnitDriver使用的WebClient。 As default the option throwExceptionOnScriptError is true. 默认情况下,throwExceptionOnScriptError选项为true。 But all the browsers are ignoring processing the javascrip if a (unhandled) exception occurs. 但是,如果发生(未处理的)异常,则所有浏览器都将忽略对Javascrip的处理。 If i got you right your page throws this exception also if running with the real browser; 如果我说对了,那么如果使用真正的浏览器运行,您的页面也会抛出该异常; means you have to 意味着你必须
Sample code: 样例代码:
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.