知识
助手
最大化  清空记录  历史记录
   1442  
查询码: 00000211
htmlunit配合jsoup获取动态页面
来源:https://blog.csdn.net/lilianggui/article/details/102539226
作者: 系统管理员 于 2020年03月08日 发布在分类 / 技术研发 / 爬虫技术 ,于 2020年03月08日 编辑
htmlunit webclient 页面 阅读 阅读数 读数 使用 来自 网页 博客

版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/lilianggui/article/details/102539226



jsoup只能解析静态的html页面,如果页面由js动态生成的,jsoup就无从下手了,使用htmlunit可以获取js运行后的页面,还可以模拟浏览器点击页面上的元素等,非常强大,本文介绍htmlunit的简单使用。步骤如下:

1、引入依赖

<dependency>
  <groupId>net.sourceforge.htmlunit</groupId>
  <artifactId>htmlunit</artifactId>
  <version>2.36.0</version>
</dependency>

<dependency>
  <groupId>org.jsoup</groupId>
  <artifactId>jsoup</artifactId>
  <version>1.12.1</version>
</dependency>

2、我们爬取自己画的页面,先画一个简单的页面,页面中id为content的div原来的内容为hello,页面加载之后,内容变成<div>HtmlUnit好强大</div>,访问一下该页面可以看到结果

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

  <h1>HtmlUnit简单使用</h1>

  <div id="content">
    hello
  </div>

</body>

<script>
  document.getElementById("content").innerHTML = "<div>HtmlUnit好强大</div>";
</script>

</html>

3、编写测试类,先使用jsoup直接爬取,看content中的内容是啥,我们打印一下,可以看到是hello

@Test
public void testJsoup() throws IOException {
  Document document = Jsoup.connect("http://localhost:8080/index.html").get();
  System.out.println(document.getElementById("content").html());
}

4、使用htmlunit之后看结果

@Test
public void test() {
  final WebClient webClient = new WebClient(BrowserVersion.CHROME);

  webClient.getOptions().setThrowExceptionOnScriptError(false);
  webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
  webClient.getOptions().setActiveXNative(false);
  webClient.getOptions().setCssEnabled(false);
  webClient.getOptions().setJavaScriptEnabled(true);
  webClient.setAjaxController(new NicelyResynchronizingAjaxController());

  HtmlPage page = null;
  try {
    page = webClient.getPage("http://localhost:8080/index.html");
  } catch (Exception e) {
    e.printStackTrace();
  }finally {
    webClient.close();
  }

  webClient.waitForBackgroundJavaScript(30000);

  String pageXml = page.asXml();
  Document document = Jsoup.parse(pageXml);//获取html文档
  System.out.println(document.getElementById("content").html());

}

可以看到是js运行之后的内容,和浏览器看到的结果一致

0人参与


 历史版本

修改日期 修改人 备注
2020-03-08 16:47:58[当前版本] 系统管理员 创建版本

 附件

附件类型

PNGPNG

wcp知识库系统-京ICP备15024440号-1 -V 5.1.3 -wcp