Selenium HtmlUnit:如何绕过JS错误?

时间:2015-10-25 03:39:41

标签: java selenium

我一直在制作一个小时的节目,我似乎无法找到一种无头和自动化的方法。

WebDriver driver = new HtmlUnitDriver(
BrowserVersion.INTERNET_EXPLORER_11, true);

driver.get("*Site Removed*"); <-- Exception is called here

需要JavaScript来实现这一点,所以我最初尝试使用FirefoxDriver来测试代码。当我在启用JS的情况下切换到HtmlUnitDriver时它工作得很好,该程序引发了一个异常,声明它无法调用方法。

错误

Exception in thread "main" org.openqa.selenium.WebDriverException: com.gargoylesoftware.htmlunit.ScriptException: TypeError: Cannot call method "toLowerCase" of undefined (script in http://***)
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:55:52'
System info: host: '**-PC', ip: '***.***.**.**', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_51'
Driver info: driver.version: HtmlUnitDriver
Driver info: driver.version: HtmlUnitDriver
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.get(HtmlUnitDriver.java:554)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.get(HtmlUnitDriver.java:530)
    at com.hazebyte.apple.AppleTest.main(AppleTest.java:26)
Caused by: com.gargoylesoftware.htmlunit.ScriptException: TypeError: Cannot call method "toLowerCase" of undefined (script in http://***)
    at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:865)
    at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:628)
    at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:513)
    at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:747)
...
Caused by: net.sourceforge.htmlunit.corejs.javascript.EcmaError: TypeError: Cannot call method "toLowerCase" of undefined (script in http://***)
    at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3935)
    at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3919)
...

错误不是因为JavaScript被禁用而是驱动程序无法调用&#34; toLowerCase等方法&#34;

如果您有修复的任何线索,我们将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试通过HtmlUnitDriver api启用javascript:

HtmlUnitDriver driver = new HtmlUnitDriver(
        BrowserVersion.INTERNET_EXPLORER_11, true);
driver.setJavascriptEnabled(true);
  

请注意,要执行此操作,您需要更改驱动程序变量   从 WebDriver HtmlUnitDriver

或者,您可以在Javascript支持下使用DesiredCapabilities for Html Unit:

WebDriver driver = new HtmlUnitDriver(DesiredCapabilities.htmlUnitWithJs());

我还不完全清楚DesiredCapabilities对HtmlUnit的影响,所以我不确定第二个选项对你的任务是否可行。它确实存在,所以如果第一个设置不起作用,可能需要考虑和进一步研究。

最好的运气。