我有一个使用HtmlUnit库的java应用程序,从xml页面获取源代码时遇到问题。我得到的只是一个" ClassCastException"错误。
我正在使用最新的HtmlUnit 2.15 API库。
public static void main(String[] args) {
WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setActiveXNative(false);
webClient.getOptions().setAppletEnabled(false);
webClient.getOptions().setCssEnabled(true);
webClient.getOptions().setPopupBlockerEnabled(true);
webClient.getOptions().setPrintContentOnFailingStatusCode(false);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.getOptions().setThrowExceptionOnScriptError(true);
webClient.getOptions().setTimeout(100000);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setDoNotTrackEnabled(false);
//webClient.getOptions().setProxyConfig(new ProxyConfig("10.0.0.1", 8080));
try{
HtmlPage page = webClient.getPage("http://www.w3schools.com/xml/note.xml");
// TODO, add your application code
System.out.println(page.asXml());
} catch (Exception e) {
System.out.println("An error occurs when getting the page: "+e);
}
}
关于如何通过htmlunit库检索xml文件并将其保存到文件的任何想法?
答案 0 :(得分:0)
我最终想通了。
转而我们首先需要导入com.gargoylesoftware.htmlunit.xml.XmlPage;
然后,您可以声明XmlPage对象,从而避免出现ClassCastException问题。
所以对于那些也是HtmlUnit
的新手,我的代码看起来像这样public static void main(String[] args) {
WebClient webClient = new WebClient(BrowserVersion.CHROME);
XmlPage page = null;
webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setActiveXNative(false);
webClient.getOptions().setAppletEnabled(false);
webClient.getOptions().setCssEnabled(true);
webClient.getOptions().setPopupBlockerEnabled(true);
webClient.getOptions().setPrintContentOnFailingStatusCode(false);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.getOptions().setThrowExceptionOnScriptError(true);
webClient.getOptions().setTimeout(100000);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setDoNotTrackEnabled(false);
//webClient.getOptions().setProxyConfig(new ProxyConfig("10.0.0.1", 8080));
try {
//go to url
page = webClient.getPage("http://www.w3schools.com/xml/note.xml");
System.out.println(xpage.asXml());
//just for test save to file to see results
File file = new File("result.html");
FileOutputStream fos = new FileOutputStream(file);
fos.write(xpage.asXml().getBytes());
fos.close();
//end test
} catch (Exception e) {
System.out.println("An error occurs when getting the page: "+e);
}
}