使用java+jsoup抓取网页数据 - Go语言中文社区

使用java+jsoup抓取网页数据


原文链接:https://www.cnblogs.com/lkxsnow/p/5380164.html

本文将博客内容写成一个demo,内含所需jar包和源码,可直接运行,下载地址:https://download.csdn.net/download/qq_30307137/10867061

首先展示我们需要抓取的网页,和抓取之后我们获得的数据:

下面开始我们的编码:

新建一个model类,是需要抓取数据的实体类:

package test;

/**
 * 万年历工具实体类
 * 
 * @author 溯源blog
 * 2016年4月11日
 */
public class Almanac {
    private String solar;        /* 阳历 e.g.2016年 4月11日 星期一 */
    private String lunar;        /* 阴历 e.g. 猴年 三月初五*/
    private String chineseAra;    /* 天干地支纪年法 e.g.丙申年 壬辰月 癸亥日*/
    private String should;        /* 宜e.g. 求子 祈福 开光 祭祀 安床*/
    private String avoid;        /* 忌 e.g. 玉堂(黄道)危日,忌出行*/

    public String getSolar() {
        return solar;
    }

    public void setSolar(String date) {
        this.solar = date;
    }

    public String getLunar() {
        return lunar;
    }

    public void setLunar(String lunar) {
        this.lunar = lunar;
    }

    public String getChineseAra() {
        return chineseAra;
    }

    public void setChineseAra(String chineseAra) {
        this.chineseAra = chineseAra;
    }

    public String getAvoid() {
        return avoid;
    }

    public void setAvoid(String avoid) {
        this.avoid = avoid;
    }

    public String getShould() {
        return should;
    }

    public void setShould(String should) {
        this.should = should;
    }

    public Almanac(String solar, String lunar, String chineseAra, String should,
            String avoid) {
        this.solar = solar;
        this.lunar = lunar;
        this.chineseAra = chineseAra;
        this.should = should;
        this.avoid = avoid;
    }
}

 

接下来是一个工具类,用来解析网页的数据并提取想要的信息

package test;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
 *<STRONG>类描述</STRONG> :  2345万年历信息爬取工具<p>
 *   
 * @version 1.0 <p>
 * @author 溯源blog
 * 
 * <STRONG>创建时间</STRONG> : 2016年4月11日 下午14:15:44<p>
 * <STRONG>修改历史</STRONG> :<p>
 *<pre>
 * 修改人                   修改时间                     修改内容
 * ---------------         -------------------         -----------------------------------
 *</pre>
 */
public class AlmanacUtil {
    
    /**
     * 单例工具类
     */
    private AlmanacUtil() {
    }
    /**
     * 获取万年历信息
     * @return
     */
    public static Almanac getAlmanac(){
        String url="http://tools.2345.com/rili.htm";//http://tools.2345.com/rili.htm
        String html=pickData(url);
        Almanac almanac=analyzeHTMLByString(html);
        return almanac;
    }
    
    /*
     * 爬取网页信息
     */
    private static String pickData(String url) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet(url);
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                // 打印响应状态
                if (entity != null) {
                    return EntityUtils.toString(entity);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    
    /*
     * 使用jsoup解析网页信息
     */
    private static Almanac analyzeHTMLByString(String html){
        
        String solarDate,lunarDate,chineseAra,should,avoid=" ";
        Document document = Jsoup.parse(html);
        //公历时间
        solarDate=getSolarDate();
        //农历时间
        Element eLunarDate=document.getElementById("info_nong");
        lunarDate=eLunarDate.child(0).html().substring(1,3)+eLunarDate.html().substring(11);
        //天干地支纪年法
        Element eChineseAra=document.getElementById("info_chang");
        chineseAra=eChineseAra.text().toString();    
        //宜
        should=getSuggestion(document,"yi");
        //忌
        avoid=getSuggestion(document,"ji");
        Almanac almanac=new Almanac(solarDate,lunarDate,chineseAra,should,avoid);
        return almanac;
    }
    /*
     * 获取忌/宜
     */
    private static String getSuggestion(Document doc,String id){
        Element element=doc.getElementById(id);
        Elements elements=element.getElementsByTag("a");
        StringBuffer sb=new StringBuffer();
        for (Element e : elements) {
            sb.append(e.text()+" ");
        }
        return sb.toString();
    }

    /*
     * 获取公历时间,用yyyy年MM月dd日 EEEE格式表示。
     * @return yyyy年MM月dd日 EEEE
     */
    private static String getSolarDate() {
        Calendar calendar = Calendar.getInstance();
        Date solarDate = calendar.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 EEEE");
        return formatter.format(solarDate);
    }

}

最后一个是测试类:

package test;

public class AlmanacUtilTest {
    
    public static void main(String args[]){
    
         Almanac almanac=AlmanacUtil.getAlmanac();
            System.out.println("公历时间:"+almanac.getSolar());
            System.out.println("农历时间:"+almanac.getLunar());
            System.out.println("天干地支:"+almanac.getChineseAra());
            System.out.println("宜:"+almanac.getShould());
            System.out.println("忌:"+almanac.getAvoid());
   
             
    }
}

到此为止,你就可以成功抓取网页的数据了

 

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_30307137/article/details/85161054
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-04-12 09:51:42
  • 阅读 ( 468 )
  • 分类:前端

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢