htmlunit抓取动态网页(Java环境下的一下配置实现思路介绍-苏州安嘉 )

优采云 发布时间: 2021-09-30 14:24

  htmlunit抓取动态网页(Java环境下的一下配置实现思路介绍-苏州安嘉

)

  在抓取网页数据的时候,传统的jsoup方案只能对静态页面有效,而且一些网页数据往往是js生成的,所以这个时候就需要其他的方案了。

  第一个思路是分析js程序,重新抓取js请求。这适用于特定页面的抓取。实现不同目标URL的通用性比较麻烦。

  第二个想法,也是更成熟的方法,是使用第三方驱动程序来呈现页面,然后下载它。这里介绍第二种实现思路。

  Selenium 是一种模拟浏览器的自动化测试工具。它提供了一组 API 来与真正的浏览器内核进行交互。

  Java环境中的maven配置如下:

  

org.seleniumhq.selenium

selenium-java

2.46.0

  第三方驱动主要有IEDriver、FirefoxDriver、ChromeDriver、HtmlUnitDriver。

  htmlUnit 也是自动化测试的工具。您可以使用 HtmlUnit 来模拟浏览器的操作来获取执行的 html 页面。其中HtmlUnitDriver是对htmlUnit的封装。

  因为htmlunit对js解析的支持有限,所以在实际项目中并不常用。

  以chrome为例下载对应的驱动:。

  下载驱动时需要注意与selenium版本的兼容性。可能会出现异常情况。一般下载最新版本即可。

  在程序运行之前必须确定驱动程序位置,例如在Windows下

  System.getProperties().setProperty("webdriver.chrome.driver",

"D:\\chromedriver\\chromedriver.exe");

  获取整个页面

   public static void testChromeDriver() {

System.getProperties().setProperty("webdriver.chrome.driver",

"D:\\chromedriver\\chromedriver.exe");

WebDriver webDriver = new ChromeDriver();

webDriver.get("http://picture.youth.cn/qtdb/201506/t20150625_6789707.htm");

String responseBody = webDriver.getPageSource();

System.out.println(responseBody);

webDriver.close();

}

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线