zoukankan      html  css  js  c++  java
  • java 利用PhantomJS 生成网页缩略图

    原文:https://www.jianshu.com/p/8210a17bcdb8

    原文:https://www.cnblogs.com/han108/p/9216583.html

    PhantomJS是一个基于webkit的JavaScript API。它使用QtWebKit作为它核心浏览器的功能,使用webkit来编译解释执行JavaScript代码。任何你可以在基于webkit浏览器做的事情,它都能做到。它不仅是个隐形的浏览器,提供了诸如CSS选择器、支持Web标准、DOM操作、JSON、HTML5、Canvas、SVG等,同时也提供了处理文件I/O的操作,从而使你可以向操作系统读写文件等。PhantomJS的用处可谓非常广泛,诸如网络监测、网页截屏、无需浏览器的 Web 测试、页面访问自动化等。

    PhantomJS官方地址:http://phantomjs.org/
      PhantomJS官方API:http://phantomjs.org/api/
      PhantomJS官方示例:http://phantomjs.org/examples/
      PhantomJS GitHub:https://github.com/ariya/phantomjs/
      PhantomJS 下载:https://phantomjs.org/download.html

    下载完成后解压文件,建议为方便使用,单独放在一个文件夹里,如放在D:workspacephantomjs里。

    到这里,你已经成功下载安装好PhantomJS了。那么,打开D:workspacephantomjsin文件夹,双击运行phantomjs.exe,出现如下界面,那么你就可以运行JS代码了。


     
    image.png

    可以考虑将D:workspacephantomjsin路径配置到环境变量中.方便日后使用

    第一个PhantomJS小程序

    // demo.js
    var page = require('webpage').create();
    phantom.cutputEncoding = 'gbk';
    page.open("https://www.jianshu.com", function(status) {
      if(status === "success") {
        page.render("jianshu.png");
      } else {
        console.log("Page failed to load.");
      };
    phantom.exit();
    });

    然后在cmd命令行中, 切换到demo.js所有目录运行demo.js.

     
    image.png

    demo.js会将抓取到页面的截图保存到当前页面
    如上图所示的 jianshu.png.

    PhantomJS核心API

    • webpage:它的作用主要是提供了一套可以访问和操作web文档的核心方法,包括操作DOM、事件捕获、用户事件模拟等等。
    • system:该模块提供了一些与操作系统相关的接口,例如访问操作系统信息、访问系统环境变量、接受命令行参数等等与程序执行相关的系统信息。
    • fs:即FileSystem。熟悉NodeJS的朋友都知道,NodeJS也内建了相关的核心模块。fs提供了执行文件I/O操作的标准接口,如读写文件、删除文件等。它使得你持久化一些文件(如logfile等)变得非常容易。
    • webserver:如其名字一样,你可以基于它来实现自己的webserver,用来处理请求并且执行PhantomJS代码等。
    Java代码
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    
    /**
     * @Description:根据网页地址转换成图片
     * @Author: admin
     * @CreateDate: 2018年6月22日
     */
    public class PhantomTools {
        private static String tempPath = "D:/temp/img";// 图片保存目录
        private static String BLANK = " ";
        // 下面内容可以在配置文件中配置
        private static String binPath = "D:/tooles/phantomjs/phantomjs-2.1.1-windows/bin/phantomjs.exe";// 插件引入地址
        private static String jsPath = "D:/tooles/phantomjs/phantomjs-2.1.1-windows/examples/rasterize.js";// js引入地址
    
        // 执行cmd命令
        public static String cmd(String imgagePath, String url) {
            return binPath + BLANK + jsPath + BLANK + url + BLANK + imgagePath;
        }
        //关闭命令
        public static void close(Process process, BufferedReader bufferedReader) throws IOException {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (process != null) {
                process.destroy();
                process = null;
            }
        }
        /**
         * @param userId 
         * @param url
         * @throws IOException 
         */
        public static void printUrlScreen2jpg(String url) throws IOException{
            String imgagePath = tempPath+"/"+System.currentTimeMillis()+".png";//图片路径
            //Java中使用Runtime和Process类运行外部程序
            Process process = Runtime.getRuntime().exec(cmd(imgagePath,url));
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String tmp = "";
            while ((tmp = reader.readLine()) != null) {
                close(process,reader);
            }
            System.out.println("success");
        }
        
        public static void main(String[] args) throws IOException {
            String url = "https://www.baidu.com/";//以百度网站首页为例
            PhantomTools.printUrlScreen2jpg(url);
        }
    }

    负责截图脚本examples文件夹下rasterize.js如下:

    var page = require('webpage').create(),
        system = require('system'),
        address, output, size;
    
    if (system.args.length < 3 || system.args.length > 5) {
        phantom.exit(1);
    } else {
        address = system.args[1];//传入url地址
        output = system.args[2];//输出图片的地址
        page.viewportSize = {  800, height: 1800 };//自定义定义宽高
        if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") {
            size = system.args[3].split('*');
            page.paperSize = size.length === 2 ? {  size[0], height: size[1], margin: '0px' }
                                               : { format: system.args[3], orientation: 'portrait', margin: '1cm' };
        } else if (system.args.length > 3 && system.args[3].substr(-2) === "px") {
            size = system.args[3].split('*');
            if (size.length === 2) {
                pageWidth = parseInt(size[0], 10);
                pageHeight = parseInt(size[1], 10);
                page.viewportSize = {  pageWidth, height: pageHeight };
                page.clipRect = { top: 0, left: 0,  pageWidth, height: pageHeight };
            } else {
                console.log("size:", system.args[3]);
                pageWidth = parseInt(system.args[3], 10);
                pageHeight = parseInt(pageWidth * 3/4, 10); // it's as good an assumption as any
                console.log ("pageHeight:",pageHeight);
                page.viewportSize = {  pageWidth, height: pageHeight };
            }
        }
        if (system.args.length > 4) {
            page.zoomFactor = system.args[4];
        }
        page.open(address, function (status) {
            if (status !== 'success') {
                console.log('Unable to load the address!');
                phantom.exit(1);
            } else {
                window.setTimeout(function () {
                    page.render(output);
                    phantom.exit();
                }, 200);//防止图片加载过慢
            }
        });
    }



  • 相关阅读:
    PythonのTkinter基本原理
    使用 Word (VBA) 分割长图到多页
    如何使用 Shebang Line (Python 虚拟环境)
    将常用的 VBScript 脚本放到任务栏 (Pin VBScript to Taskbar)
    关于 VBScript 中的 CreateObject
    Windows Scripting Host (WSH) 是什么?
    Component Object Model (COM) 是什么?
    IOS 打开中文 html 文件,显示乱码的问题
    科技发展时间线(Technology Timeline)
    列置换密码
  • 原文地址:https://www.cnblogs.com/BambooLamp/p/12850372.html
Copyright © 2011-2022 走看看