htmlUnit 静态化 页面(目前,我能用的唯一方法)
ajax异步加载的页面,用htmlUnit来静态化页面,思想是:做2个模板,一个采用页面加载的时候 同步 加载 ajax数据,把加载完的页面的内容复制到第2个模板,再将第2个模板保存,这样用户直接访问静态页面。(备注:第二个模板其实只是加载页面的时候不再加载数据,因为要另存为静态页面)
大致思路是这样的,代码如下(这里是静态产品页面的htmlUnit代码):
public static void productzAllToHtml() {
try {
// 创建一个可执行js,css,ajax的多功能WebClient
WebClient multiWebClient = new WebClient(
BrowserVersion.INTERNET_EXPLORER_8);
multiWebClient.setJavaScriptEnabled(true);// 执行JavaScript
multiWebClient.setCssEnabled(true);// 执行css
multiWebClient
.setAjaxController(new NicelyResynchronizingAjaxController());// 设置ajax代理
// 上面加载一个动态的页面(模板1)
// 创建一个普通的WebClient
WebClient commmonWebClient = new WebClient(
BrowserVersion.INTERNET_EXPLORER_8);
commmonWebClient.setJavaScriptEnabled(true);
commmonWebClient.setCssEnabled(false);
//上面是模板2
// 下面是分别加载页面,并执行js
URL dynamicUrl = new URL("http://localhost/fangnw/productzAll.html");
HtmlPage dynamicPage = (HtmlPage) multiWebClient
.getPage(dynamicUrl);//加载动态页面,ajax执行,
// 根据项目需要,使用普通Client加载首页模板(避免执行模板里面的js,这些js都是真正要浏览器查看的时候才会执行)
URL constantUrl = new URL(
"http://localhost/fangnw/productzAll_m.html");
HtmlPage htmlpage = (HtmlPage) commmonWebClient
.getPage(constantUrl);
//这里是动态页面内容copy到静态模板里面
htmlpage.getElementById("contain_in").replace(
dynamicPage.getElementById("contain_in"));
//这里是保存,采用asXML()方法,就是这里,页面保存后变成xml了,我希望是html,没有asHTML()方法啊??
stringToFile(htmlpage.asXml(), "E:\\productzAll_d.html");
// 关闭浏览器
multiWebClient.closeAllWindows();
commmonWebClient.closeAllWindows();
} catch (Exception e) {
e.printStackTrace();
}
}
/保存文件的工具函数
public static void stringToFile(String content, String path) {
try {
FileWriterWithEncoding fileWriter = new FileWriterWithEncoding(
path, "utf-8");
fileWriter.write(content);
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
请问,如何保存为 html页面呢? 我希望htmlUnit中有这样的方法,只是我没有找到,请大家帮助啊!!
(我能想到的其他解决方法:通过java删除xml的<? version="1.0" ...>头部.在添加 html的 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">)
下面是我静态后的页面头部文件:
<?xml version="1.0" encoding="utf-8"?> //好端端的html 被搞成xml的,这里怎么修改啊?
<html>
<head>
<base target="_blank"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>
【北京新房_潮白河孔雀城 】-九房网
</title>
<link href="./css/productInfo.css" rel="stylesheet" type="text/css"/>
我希望保存后的是:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html> //这个才是html啊,css才能有横好的效果
<head>
<base target="_blank"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>
【北京新房_潮白河孔雀城 】-九房网
</title>
<link href="./css/productInfo.css" rel="stylesheet" type="text/css"/>
具体请大家 访问:http://www.jiu30.com 网站,在网站地图下面可以静态页面,网站其他地方时动态页面!
希望得到大家的帮助 谢谢! 我的qq12327649 ,欢迎一起学习 谢谢