美文网首页程序员
java 利用chrome+puppeteer实现爬虫

java 利用chrome+puppeteer实现爬虫

作者: 梦将空 | 来源:发表于2019-01-28 17:57 被阅读0次

    java在进行爬虫过程中会因为网站作出反爬措施,导致抓取的内容不全面,所以需要利用模拟浏览器,打开页面获取到页面的全部内容。本文以腾讯新闻https://news.qq.com/为例。
    环境配置参考https://www.jianshu.com/p/6c3d90bef17f,可以配置nodejs的环境。
    一、使用jsoup解析网页,当解析腾讯新闻时只能获取到网页的源码,其他与新闻相关的内容一概获取不到,从而无法抓取到有用的信息。

    /**
     * 利用jsoup解析网页
     * @param url
     * @return
     */
    public static Document getDocumentByJsoup(String url){
        Document document = null;
        try {
            document = Jsoup.connect(url).timeout(15000).get();
            String text = document.getElementsByTag("body").text();
            System.err.println(text);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return document;
    }
    

    测试获取的结果,获取不到新闻列表


    result.png

    二、利用chrome + nodejs的方式进行测试。

    /**
     * 利用chrome方式获取页面信息
     * @param url
     * @return
     */
    public static Document getDocument(String url){
        Document document = null;
        //chrome浏览器地址
        String chromePath = "你的chrome浏览器根目录";
        
        //nodejs地址  + 截图的js的地址(两个需要在同一个目录之下)
        String nodeJSPath = "nodejs根目录地址   渲染页面所需要的js根目录地址.js";
        
        String BLANK = "    ";
        
        String exec =  nodeJSPath + BLANK + chromePath + BLANK + url;
        
        try {
            //执行脚本命令
            Process process = Runtime.getRuntime().exec(exec);
            
            System.err.println("ecec =======> " + exec);
            
            InputStream is = process.getInputStream();
            document = Jsoup.parse(is, "UTF-8", url);
          
            try {
                process.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
    
            process.destroy();
            process = null;
             
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return document;
    }
    

    运行获取到的结果


    result2.png

    而在任务执行过程中所需要的渲染页面的js


    render.png

    写好js后可以利用cdm进行测试。java中也可以利用相同的方法进行截图。只需要在程序中将js换掉就行。并增加一个参数


    截图地址.png

    截图所需要的js


    截图

    相关文章

      网友评论

        本文标题:java 利用chrome+puppeteer实现爬虫

        本文链接:https://www.haomeiwen.com/subject/nztmjqtx.html