java简单的爬虫(今日头条)

之前在做资讯站的时候需要用到爬虫来获取一些文章,今天刚好有空就研究了一下.在网上看到了一个demo,使用的是Jsoup,我拿过来修改了一下,
由于今日头条的文章的特殊性,所以无法直接获取文章的地址,需要获取文章的id然后在拼接成url再访问.

public class Demo2 {

 public static void main(String[] args) {

    // 需要爬的网页的文章列表
    String url = "http://www.toutiao.com/news_finance/";
    //文章详情页的前缀(由于今日头条的文章都是在group这个目录下,所以定义了前缀,而且通过请求获取到的html页面)
    String url2="http://www.toutiao.com/group/";
    //链接到该网站
    Connection connection = Jsoup.connect(url);
    Document content = null;
    try {
        //获取内容
        content = connection.get();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //转换成字符串
    String htmlStr = content.html();
    //因为今日头条的文章展示比较奇葩,都是通过js定义成变量,所以无法使用获取dom元素的方式获取值
    String jsonStr = StringUtils.substringBetween(htmlStr,"var _data = ", ";");
    System.out.println(jsonStr);
    Map parse = (Map) JSONObject.parse(jsonStr);
    JSONArray parseArray = (JSONArray) parse.get("real_time_news");
    Map map=null;
    List<Map> maps=new ArrayList<>();
    //遍历这个jsonArray,获取到每一个json对象,然后将其转换成Map对象(在这里其实只需要一个group_id,那么没必要使用map)
    for(int i=0;i<parseArray.size();i++){
        map = (Map)parseArray.get(i);
        maps.add((Map)parseArray.get(i));
        System.out.println(map.get("group_id"));
        
    }
    //遍历之前获取到的map集合,然后分别访问这些文章详情页
    for (Map map2 : maps) {
        connection = Jsoup.connect(url2+map2.get("group_id"));
        try {
            Document document = connection.get();
            //获取文章标题
            Elements title = document.select("[class=article-title]");
            System.out.println(title.html());
            //获取文章来源和文章发布时间
            Elements articleInfo = document.select("[class=articleInfo]");
            Elements src = articleInfo.select("[class=src]");
            System.out.println(src.html());
            Elements time = articleInfo.select("[class=time]");
            System.out.println(time.html());
            //获取文章内容
            Elements contentEle = document.select("[class=article-content]");
            System.out.println(contentEle.html());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,117评论 25 708
  • 爬虫文章 in 简书程序员专题: like:128 - Python 爬取落网音乐 like:127 - 【图文详...
    treelake阅读 29,582评论 33 638
  • 今天咱来说说关于古典的一些事情。 先引用一下定义,古典这个定义就是:以一种严肃考究,并且含有一定的形式...
    烟老师阅读 366评论 0 0
  • 人老了,就像这树上的叶子,终究是要凋零的。
    简记微语阅读 153评论 0 0
  • 其实画画可以让心很静,即使画的不够好,也是画的一种心情。 绘画最主要的要有耐心,画多了,每个人都是大师...
    快乐的Alina阅读 375评论 2 2