分享一些htmlunit实际使用过程中遇到的问题。
1、解析js失败
下面这个是我用htmlunit模拟访问我们公司的一个vue项目时,遇到的报错。
@Test public void test1() throws IOException, SAXException { System.out.println("hello world"); WebClient webClient = new WebClient(BrowserVersion.CHROME); webClient.getOptions().setCssEnabled(false); webClient.getOptions().setJavaScriptEnabled(true); HtmlPage htmlpage = webClient.getPage("http://177.61.11.999:8080/"); }
HtmlPage htmlpage = webClient.getPage("http://177.61.11.999:8080/"); 这行getPage报错。
======= EXCEPTION START ========
EcmaError: lineNumber=[1] column=[0] lineSource=[<no source>] name=[TypeError] sourceName=[http://10.1.3.32:8080/cdn/vxe-table/vxe-table.js] message=[TypeError: Expected argument of type object, but instead had type object (http://10.1.3.32:8080/cdn/vxe-table/vxe-table.js#1)
]
com.gargoylesoftware.htmlunit.ScriptException: TypeError: Expected argument of type object, but instead had type object (http://10.1.3.32:8080/cdn/vxe-table/vxe-table.js#1)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:705)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:620)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:513)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:591)
EcmaError: lineNumber=[1] column=[0] lineSource=[<no source>]
这一行表示,htmlunit在解析这个js文件时,从第一个字符就开始报错,解析js失败。
我找到这个js的代码发现,这个js并没有什么问题。问题就出在htmlunit对他的解析上。
解决办法:方式1、webclient.getOptions.setJavaScriptEnable(true); true改成false
禁用js,或者报错就没有了。这个就属于是掩耳盗铃,脚疼跺脚,禁用js那所有动态内容都拿不到了,不报错也没什么意义。
方式2 、更换更高htmlunit版本
我更换了2.15、2.34以及最新的2.7版本。都没有解决这个问题。在使用2.7版本的时候,出现了栈溢出。可以看出来htmlunit是比较努力的解决这个问题的,但是很遗憾他失败了。
如果你遇到同样的问题,js解析失败,更换版本也许有用,理论上越高版本对js的支持也就越好。
方式3、give up
适时选择放弃,死磕没有意义。这个页面你注定扒不了了。换个页面。
我最终选择方式3.
总结:htmlunit对js的支持是有限的,有的就是不支持。