在JAVA中通过jsoup获取url中的html元素的简单代码示例

jsoup解析url中的html元素

有时候需要通过解析不同网站的网站元素、数据等信息做些基本的调研或者分析。随着技术的不断发展及升级,很多网站已经升级使用vue或者相关前端框架作为首选。这样的话,使用jsoup方式无法内容元素,因为内容不是即时输出到页面上,而是通过js动态渲染。这种情况的话需要配合selenium浏览器测试工具处理,配合相关浏览器的驱动程序,也比较好用。下面先放出jsoup方式

bing搜索的解析代码如下

动作:获取输入搜索词后的首页列表标题 + 链接

package org.crawler.spider;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;


/**
 * 利用java-urlConnection解析url中的html代码,获取相关信息元素
 * 
 * @author chenhailong
 * @date 2018年10月22日 下午7:13:02 
 */
public class test {

  /**
   * @param args
   */
  public static void main(String[] args) {
    
    try {
      
      String path = "https://cn.bing.com/search?q=site%3Awww.deathearth.com&qs=n&form=QBLH&sp=-1&pq=site%3Awww.deathearth.com&sc=0-23&sk=&cvid=AC9F8650E83543C093114B16157FD8DC";
      
      Document listPage = getUrlDoc(path);
      //找到内容版面
      Element ele = listPage.getElementById("b_results");   
      //如果页面中有多个id值,会找不到元素
      //listPage.getElementById("content_left")  
      
      //找到列表块,排除一些个性化展示内容,如果引用多个样式,需要用下面这种方式
      //List<Element> es = ele.select("div.result.c-container");
      
      List<Element> es = ele.getElementsByClass("b_algo");
      for(Element e: es) {
        String title = e.getElementsByTag("h2").get(0).text();
        String href  = e.child(0).childNode(0).attr("href");
        System.out.println("标题:"+ title);
        System.out.println("连接:"+ href);
        
        //开始解析详细页面
        //Document detail = getUrlDoc(href);
        
      }
      
      
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  
  /**
   * 根据路径获取当前页面html
   * @param path 路径-url
   * @return 文档对象,如流为0,则返回null
   */
  public static Document getUrlDoc(String path) {
    String html = ""; //最终的html源码
    try {
      URL u = new URL(path);
      URLConnection url = u.openConnection();
      //将流转换为字符
      html = convertStreamToString(url.getInputStream());
    } catch (IOException e) {
      e.printStackTrace();
    }
    if(html.length() < 1) {
      return null;
    }else {
      Document doc = Jsoup.parse(html);
      return doc;
    }
  }
  
  
  /**
   * 将InputStream转化为String
   * @param is 流
   * @return 当前url文本
   * @throws IOException
   */
  public static String convertStreamToString(InputStream is) throws IOException {
      if (is == null)
          return "";
      //将输出流转换编码
      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
      StringBuilder sb = new StringBuilder();
      String line = null;
      try {
          while ((line = reader.readLine()) != null) {
              sb.append(line);
          }
      } catch (IOException e) {
          e.printStackTrace();
      } finally {
          try {
              is.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
      reader.close();
      return sb.toString();
  }
}

执行结果如下

标题:一个程序猿的编码人生
连接:https://www.deathearth.com/
标题:servlet2.5升级servlet3.1/servlet4.0的新特性(注解替换web …
连接:https://www.deathearth.com/834.html
标题:《java开发手册》1.5.0华山版云盘下载,阿里巴巴集团技术 …
连接:https://www.deathearth.com/881.html
标题:脚本清理最近X日之前的ELK日志文件,优化磁盘空间 - 程序猿 …
连接:https://www.deathearth.com/370.html
标题:java使用transportClient连接elasticsearch并做接口实现增删改 …
连接:https://www.deathearth.com/651.html
标题:使用AOP拦截controller层方法时,通过监控方法上的注解 …
连接:https://www.deathearth.com/227.html
标题:SpringBoot改造异常:Invalid bean definition with name …
连接:https://www.deathearth.com/549.html
标题:环境搭建-Eclipse安装Spring-Tool-Sutite插件并创建简单的 …
连接:https://www.deathearth.com/455.html
标题:windows10_x64下配置hadoop2.7.5的环境搭建介绍 - 程序猿 …
连接:https://www.deathearth.com/67.html
标题:elasticsearch6.4.2安装x-pack安全认证后,java如何使用 …
连接:https://www.deathearth.com/679.html

总结整理

这种方式只适合还没有进行vue改造的网站,有较完整的api封装调用简便。其他工具处理对于元素的获取大同小异,还是最终根据需求选择

如:
Scrapy根据XPATH解析页面内容、下载为json格式文件、抓取列表页等的简单示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值