gpt4 book ai didi

Java htmlUnit获取xml页面ClassCastException问题

转载 作者:太空宇宙 更新时间:2023-11-04 14:22:56 24 4
gpt4 key购买 nike

我有一个使用 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 文件并将其保存到文件有什么想法吗?

最佳答案

我终于明白了。

变成我们首先需要导入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);

}

}

关于Java htmlUnit获取xml页面ClassCastException问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26987714/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com