今天学习用htmlunit来获取动态网页加载后的页面代码,也是在网上看的。自己拿来测试了一下,发现能用,而且设置很简单,之前我请求网页用的是httpClient,这个类不能运行Js代码,设置也比较复杂。但是htmlunit就很好的解决了js代码运行的问题。
首先要引入相应的包,用maven导入。
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.23</version>
</dependency>
然后编写测试类
import java.io.IOException;
import java.net.MalformedURLException;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class TestHtml {
public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
WebClient webClient= new WebClient(BrowserVersion.CHROME);//设置浏览器
webClient.getOptions().setCssEnabled(true);//设置css是否生效
webClient.getOptions().setJavaScriptEnabled(true);//设置js是否生效
webClient.setAjaxController(new NicelyResynchronizingAjaxController());//设置ajax请求
webClient.getOptions().setTimeout(10000);
webClient.waitForBackgroundJavaScript(3000);
HtmlPage htmlPage=webClient.getPage("http://localhost:8081/myweb/test.jsp");//访问路径设置
System.out.println(htmlPage.asXml());
webClient.close();
}
}
之后编写了一个jsp页面,页面加载后会替换标题里的hi改为hello,比较重要的一点是,ajax请求中的异步要设置成false,让请求同步执行,否则不起作用
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(function(){
$.ajax({
url:"test.do",
data:{"word":"hello"},
type:"post",
dataType:"text",
async:false,
success:function(result){
$("#h1").html(result);
}
});
});
</script>
</head>
<body>
<h1 id="h1">hi</h1>
</body>
</html>
最后编写一个Controller用于返回ajax请求
@Controller
public class TestController {
@RequestMapping("/test.do")
@ResponseBody
public String test(String word){
return word;
}
}
配置spring等步骤,启动tomcat成功后,运行测试类就可以在控制栏看到加载完成后的html代码了标题中的hi,变为hello了