如何忽略与jQuery相关的HTMLUnit警告/错误?
是否有可能教HTMLUnit忽略网页上的某些 JavaScript脚本/文件? 其中一些只是我的控制(如jQuery),我不能对它们做任何事情。 警告很烦人,例如:
[WARN] com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument: getElementById(script1299254732492) did a getElementByName for Internet Explorer
实际上我正在使用JSFUnit,HTMLUnit在它下面工作。
如果您因为任何JavaScript错误而想避免exception:
webClient.setThrowExceptionOnScriptError(false);
好吧,我还没有找到办法,但我找到了一个有效的解决方法。 尝试实现FalsifyingWebConnection
。 请看下面的示例代码。
public class PinConnectionWrapper extends FalsifyingWebConnection { public PinConnectionWrapper(WebClient webClient) throws IllegalArgumentException { super(webClient); } @Override public WebResponse getResponse(WebRequest request) throws IOException { WebResponse res = super.getResponse(request); if(res.getWebRequest().getUrl().toString().endsWith("/toolbar.js")) { return createWebResponse(res.getWebRequest(), "", "application/javascript", 200, "Ok"); } return res; } }
在上面的代码中,只要HtmlUnit请求toolbar.js,我的代码就会返回一个假的空响应。 您可以将上面的包装类插入到HtmlUnit中,如下所示。
final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6); new PinConnectionWrapper(webClient);
看一下WebClient.setScriptPreProcessor 。 它将使您有机会在执行之前修改(或在您的情况下,停止)给定脚本。
此外,如果只是警告让你紧张,我会建议更改日志级别 。
如果您对忽略所有警告日志条目感兴趣,可以在log4j.properties文件中为com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument将日志级别设置为INFO。
LogFactory.getFactory()。setAttribute(“org.apache.commons.logging.Log”,“org.apache.commons.logging.impl.NoOpLog”); java.util.logging.Logger.getLogger( “com.gargoylesoftware.htmlunit”)setLevel(Level.OFF)。 java.util.logging.Logger.getLogger( “org.apache.commons.httpclient”)setLevel(Level.OFF)。
插入此代码。