使用PHANTOMJS對網頁截屏


  PhantomJS 是一個基於 WebKit 的服務器端 JavaScript API。它全面支持web而不需瀏覽器支持,其快速,原生支持各種Web標准: DOM 處理, CSS 選擇器, JSON, Canvas, 和 SVG。 PhantomJS 可以用於 頁面自動化 , 網絡監測 , 網頁截屏 ,以及 無界面測試 等。

開始

1、下載phantomjs

  在http://phantomjs.org/download.html中下載phantomjs,我這里是在window系統下面操作的,所以我這里就下載第一個window版本。

2、解壓phantomjs並配置環境變量

  下載完成之后,我這邊放在E盤的,解壓到當前文件夾,我這里的路徑就是E:\phantomjs-2.1.1-windows。把路徑E:\phantomjs-2.1.1-windows\bin添加至環境變量path里面。在cmd命令行中使用phantomjs --version能看見版本號,就表示設置成功了。在cmd命令中使用phantomjs E:/phantomjs-2.1.1-windows/examples/hello.js 就可以看見Hello, world!表示可以使用了。

3、java使用phantomjs案例(對網頁截屏)

  如果我們想在java里面種使用,直接通過Process執行cmd命令就行了,請看下面例子

復制代碼
    public static void main(String[] args){  
        String url = "http://news.baidu.com";
        String saveImgPath = "C:\\Users\\Administrator\\Desktop\\百度新聞.png";
         
        String path = "E:/phantomjs-2.1.1-windows/";
        Runtime rt = Runtime.getRuntime();  
        try {  
            Process p = rt.exec(path + "/bin/phantomjs.exe "+ path +"examples/rasterize.js " + url.trim() + " " + saveImgPath ); 
            p.waitFor();
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }
復制代碼

  修改E:/phantomjs-2.1.1-windows/examples/rasterize.js

復制代碼
"use strict";
var page = require('webpage').create(),
    system = require('system'),
    address, output, size;

    address = system.args[1];//需要截圖的地址
    output = system.args[2];//截圖保存位置
    page.viewportSize = { width: 1360, height: 600 };
    page.open(address, function (status) {
        if (system.args.length > 3 ) {//截圖的寬高
            console.log("three param!");
            size = system.args[3].split('*');
            if (size.length === 2) {
                page.viewportSize = { width: size[0], height: size[1]};
                page.clipRect = { top: 0, left: 0, width: size[0], height: size[1] };//從什么地方開始截圖、到什么地方結束
            }
        }else {
            // 通過在頁面上執行腳本獲取頁面的渲染高度
            var bb = page.evaluate(function () { 
                return document.getElementsByTagName('html')[0].getBoundingClientRect(); 
            });
            // 按照實際頁面的高度,設定渲染的寬高
            page.viewportSize = { width: bb.width, height: bb.height};
            page.clipRect = {
                top:    bb.top,
                left:   bb.left,
                width:  bb.width,
                height: bb.height
            };
        }
    
        
        if (system.args.length > 4) {//截圖比例
            console.log("four param!bili:" + system.args[4]);
            page.zoomFactor = system.args[4];
        }
        
        if (status !== 'success') {
            console.log('Unable to load the address!');
            phantom.exit(1);
        } else {
            window.setTimeout(function () {
                page.render(output);
                phantom.exit();
            }, 5000);
        }
    });
復制代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM