【爬虫】简单的Java爬虫,爬取Sogou微信的首页热门文章

5 篇文章 0 订阅
5 篇文章 0 订阅

工作中遇到了一个场景,需要使用Sogou微信的热门文章做展示,调研了一段时间,没有发现有比较好用的免费接口,所以自己写了一个,非常简单。

保存Sogou热门文章需要的类:

/**
 * @author TangLei
 */
public class Article{

    //头像图片
    private String headImg;
    //标题
    private String topic;
    //文章链接
    private String articleUrl;
    //文章图片
    private String articleImg;
    //阅读次数
    private String readCount;
    //时间戳
    private String time;

    public String getHeadImg() {
        return headImg;
    }

    public void setHeadImg(String headImg) {
        this.headImg = headImg;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public String getArticleUrl() {
        return articleUrl;
    }

    public void setArticleUrl(String articleUrl) {
        this.articleUrl = articleUrl;
    }

    public String getArticleImg() {
        return articleImg;
    }

    public void setArticleImg(String articleImg) {
        this.articleImg = articleImg;
    }

    public String getReadCount() {
        return readCount;
    }

    public void setReadCount(String readCount) {
        this.readCount = readCount;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }
}

爬虫实现:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;

/**
 * 网络爬虫,获取搜狗微信搜索_订阅号及文章内容
 * @author TangLei
 */
public class Crawler {

    public String doCrawler(String url) {
        return dealPage(getPage(url));
    }

    /**
     * 读取整个网页
     * 
     * @param url:网页地址
     * @return 整个网页的内容
     */
    private String getPage(String url) {
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.connect();
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line).append("\r\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("read web page error : " + e.getMessage());
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("close reader error : " + e.getMessage());
            }
        }
        return buffer.toString();
    }

    /**
     * 对读取到的网页进行处理截取有用信息
     * 
     * @param page
     *            网页内容
     * @return 截取到的信息
     */
    private String dealPage(String page) {

        //所有的正则表达式
        Pattern[] patterns = new Pattern[4];
        patterns[0] = Pattern.compile("<p><img src=\"[a-zA-z]+://[^\\s]*");
        patterns[1] = Pattern.compile("<h4><a uigs=.*</a></h4>");
        patterns[2] = Pattern.compile("<img src=.*\" onload=\"vrImgLoad\\(this,'fit',110,110\\)\"");
        patterns[3] = Pattern.compile("阅读&nbsp;.*</bb>");

        //首先计算有多少篇文章
        int articleCount = 0;
        Matcher matcher = patterns[0].matcher(page);
        while (matcher.find()) {
            articleCount++;
        }

        //根据文章数量创建相应长度的数组
        Article[] articles = new Article[articleCount];
        for (int i = 0; i < articleCount; i++) {
            articles[i] = new Article();
        }

        //开始处理
        int index = 0;
        for (int i = 0; i < patterns.length; i++) {

            index = 0;
            matcher = patterns[i].matcher(page);
            while (matcher.find()) {
                String find = matcher.group();
                if(i==0){
                    String[] splits = find.split("\"");
                    if(index<articleCount){
                        articles[index].setHeadImg(splits[1]);
                    }
                }else if (i == 1){
                    String[] splits = find.split("\"");
                    if(index<articleCount){
                        articles[index].setArticleUrl(splits[3]);
                        articles[index].setTopic(splits[6].substring(1,splits[6].length()-9));
                    }
                }else if (i == 2){
                    String[] splits = find.split("\"");
                    if(index<articleCount){
                        articles[index].setArticleImg(splits[1]);
                    }
                }else if (i == 3){
                    String[] splits = find.split("&nbsp;");
                    if(index<articleCount){
                        articles[index].setReadCount(splits[1]);
                        articles[index].setTime(splits[4].substring(13, 23));
                    }
                }
                index++;
            }
        }
        return JSON.toJSONString(articles);
    }

    public static void main(String[] args) throws Exception {
        String url = "http://weixin.sogou.com";
        Crawler crawler = new Crawler();
        System.out.println(crawler.doCrawler(url));
    }
}

非常简单的一个爬虫,可以参考一下,作为爬虫入门看一下也非常好。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
爬虫(Web Crawler)是一种自动化程序,用于从互联网上收集信息。其主要功能是访问网页、提数据并存储,以便后续分析或展示。爬虫通常由搜索引擎、数据挖掘工具、监测系统等应用于网络数据抓的场景。 爬虫的工作流程包括以下几个关键步骤: URL收集: 爬虫从一个或多个初始URL开始,递归或迭代地发现新的URL,构建一个URL队列。这些URL可以通过链接分析、站点地图、搜索引擎等方式获。 请求网页: 爬虫使用HTTP或其他协议向目标URL发起请求,获网页的HTML内容。这通常通过HTTP请求库实现,如Python中的Requests库。 解析内容: 爬虫对获的HTML进行解析,提有用的信息。常用的解析工具有正则表达式、XPath、Beautiful Soup等。这些工具帮助爬虫定位和提目标数据,如文本、图片、链接等。 数据存储: 爬虫将提的数据存储到数据库、文件或其他存储介质中,以备后续分析或展示。常用的存储形式包括关系型数据库、NoSQL数据库、JSON文件等。 遵守规则: 为避免对网站造成过大负担或触发反爬虫机制,爬虫需要遵守网站的robots.txt协议,限制访问频率和深度,并模拟人类访问行为,如设置User-Agent。 反爬虫应对: 由于爬虫的存在,一些网站采了反爬虫措施,如验证码、IP封锁等。爬虫工程师需要设计相应的策略来应对这些挑战。 爬虫在各个领域都有广泛的应用,包括搜索引擎索引、数据挖掘、价格监测、新闻聚合等。然而,使用爬虫需要遵守法律和伦理规范,尊重网站的使用政策,并确保对被访问网站的服务器负责。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值