phantomjs的使用+Java代码+依赖js(兼容Linux和windows版本)

1、  在使用phantomjs的时候需要下载phantomjs,网上有window版本和Linux版本。将phantomjs放在Linux上的指定位置之后(如下面的/home/tpl/phantomjs-1.9.7-linux-x86_64/处),

2、  按照类似如下命令进行测试,是否可以生成图片(执行前检查phantomjs的权限,要有执行权限):


/home/tpl/phantomjs-1.9.7-linux-x86_64/bin/phantomjs

/home/tpl/phantomjs-1.9.7-linux-x86_64/examples/test.js      

http://www.baidu.com

/home/test/index.png

注意上面的命令,每个之间用空格隔开,其中:

/home/tpl/phantomjs-1.9.7-linux-x86_64/bin/phantomjs表示的是phantomjs所在的位置

/home/tpl/phantomjs-1.9.7-linux-x86_64/examples/test.js表示使用快照的时候需要的一个js

http://www.baidu.com  要生成快照的页面

/home/test/index.png  表示要将截的图放在的位置

 

3、要使用程序生成快照,需要执行shell命令或者cmd命令

能够兼容java和windows的一段java代码如下:


package xxxxx.webservice.snapshot;

 

import java.io.BufferedReader;

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.URL;

 

import com.ucap.utils.OsUtils;

 

/**

 * SnapshotServiceImpl.java 用于生成快照的服务类

 *

 * @attention 使用注意事项

 * @author

 * @date

 * @note begin modify by 涂作权 2016-5-19 判断在Linux上的情况

 */

public class SnapshotServiceImpl implements SnapshotService {

 

         /**

          * phantomjsPath   :phantomjs

          *     /home/tpl/phantomjs-1.9.7-linux-x86_64/bin/phantomjs

          *     /home/tpl/phantomjs-1.9.7-linux-x86_64/examples/test.js 

          *     http://xxxxx:5555/tpl/special/2016/5/19/2d0cd5d12a974e438a2f4a13300f60d2/index.html

          *    

          * exportPath      :导出路径,这是一个绝对路径 

          *

          * 关于phantomjs的执行命令如:

          *     /home/tpl/phantomjs-1.9.7-linux-x86_64/bin/phantomjs

          *     /home/tpl/phantomjs-1.9.7-linux-x86_64/examples/test.js

          *     http://xxxx:5555/tpl/special/2016/5/19/2d0cd5d12a974e438a2f4a13300f60d2/index.html

          *     /home/test/index.png

          */

         public String createSnapshot(String phantomjsPath, String exportPath) {

                   URL path = this.getClass().getClassLoader().getResource("/");

                   String str = path.getPath();

                   File file = new File(str);

                   str = file.getParentFile().getParentFile().getParentFile()

                                     .getAbsolutePath()

                                     + "/temp" + exportPath;

 

                   String[] strArray = null;

 

                   // 判断linux的执行情况

                   if (OsUtils.IS_LINUX) {

                            strArray = new String[3];

                            strArray[0] = "/bin/sh";

                            strArray[1] = "-c";

                            strArray[2] = phantomjsPath + " " + str;

                   } else if (OsUtils.IS_WINDOWS) {

                            strArray = new String[4];

                            strArray[0] = "cmd.exe";

                            strArray[1] = "/C";

                            strArray[2] = phantomjsPath;

                            strArray[3] = str;

                   }

 

                   File fileInfo = new File(str);

                   File fi = new File(fileInfo.getParentFile().getAbsolutePath());

                   if (!fi.exists()) {

                            fi.mkdirs();

                   }

 

                   // windows下phantomjs位置

                   Runtime rt = Runtime.getRuntime();

                   Process process = null;

                   try {

                            process = rt.exec(strArray);

                   } catch (IOException e) {

                            e.printStackTrace();

                   }

                   StringBuffer sbf = null;

                   InputStream is = null;

                   try {

                            is = process.getInputStream();

                            BufferedReader br = new BufferedReader(new InputStreamReader(is));

                            sbf = new StringBuffer();

                            String tmp = "";

 

                            while ((tmp = br.readLine()) != null) {

                                     sbf.append(tmp);

                            }

                   } catch (IOException e) {

                            e.printStackTrace();

                   } finally {

                            if (is != null) {

                                     try {

                                               is.close();

                                     } catch (IOException e) {

                                               e.printStackTrace();

                                     }

                                     is = null;

                            }

                   }

 

                   return sbf.toString();

         }

}

其中一个依赖的test.js如下:


var page = require('webpage').create();

 

//-----------------------------获取窗口的宽高信息,并设置,write by 涂作权 start------------------------------------

var winWidth = null;

var winHeight = null;

// 获取窗口宽度

if (window.innerWidth) {

    winWidth = window.innerWidth;

} else if ((document.body) && (document.body.clientWidth)) {

    winWidth = document.body.clientWidth;

}

// 获取窗口高度

if (window.innerHeight) {

    winHeight = window.innerHeight;

} else if ((document.body) && (document.body.clientHeight)) {

    winHeight = document.body.clientHeight;

}

// 通过深入 Document 内部对 body 进行检测,获取窗口大小

if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) {

    winHeight = document.documentElement.clientHeight;

    winWidth = document.documentElement.clientWidth;

}

page.viewportSize = {width:winWidth,height:winHeight};

page.clipRect = {top:0,left:0,width:winWidth,height:winHeight};

//-----------------------------获取窗口的宽高信息,并设置end--------------------------------------

//-----------------------------------------------------------------------------------------------

page.settings = {

         javascriptEnabled:false,

         loadImages:true,

         userAgent:'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) PhantomJS/19.0'

};

//-----------------------------------------------------------------------------------------------

 

 

system = require('system');

//var url = 'http://yule.club.sohu.com/gifttrade/thread/2m2efbrpfui';

var address;

var loca;

if(system.args.length == 1){

         phantom.exit();

}else{

         adress = system.args[1];

         loca = system.args[2];

         page.open(adress, function (status){

    if (status != "success"){

        console.log('FAIL to load the address');

        phantom.exit();

    }

       

    page.evaluate(function(){

        //此函数在目标页面执行的,上下文环境非本phantomjs,所以不能用到这个js中其他变量      

        //window.scrollTo(0,10000);//滚动到底部

                   //滚动到自适应高度

        //window.document.body.scrollTop = document.body.scrollHeight;

       

       /* window.setTimeout(function(){

            var plist = document.querySelectorAll("a");

            var len = plist.length;

            while(len)

            {

                len--;

                var el = plist[len];

                el.style.border = "1px solid red";

            }

        },5000);*/

    });

   

    window.setTimeout(function (){

                       //在本地生成截图

                            page.render(loca);      

                            //console.log(loca);

                            phantom.exit();

                   }, 1000);

         });

}

 

时间: 2024-08-02 22:10:25

phantomjs的使用+Java代码+依赖js(兼容Linux和windows版本)的相关文章

代码-ajaxuploadfile.js兼容IE9

问题描述 ajaxuploadfile.js兼容IE9 我在ajaxuploadfile.js中加了兼容IE9的代码 但是在IE9下报语法错误怎么回事

js两侧图片代码为什么不兼容ff 在ie中正常显示

问题描述 js两侧图片代码为什么不兼容ff 在ie中正常显示 我是新手 js两侧图片代码为什么不兼容ff 在ie中正常显示,在ff中图片跑到网站下面了并且网页左下面只显示一张 请高手解决 js代码如下:function initEcAd() {document.all.AdLayer1.style.posTop = -200;document.all.AdLayer1.style.visibility = 'visible'document.all.AdLayer2.style.posTop =

javascript-js中的java代码如何访问js中方法的参数??见图

问题描述 js中的java代码如何访问js中方法的参数??见图 如何让1处的值传到2处这里?? 解决方案 需要用ajax提交你的index到服务器,服务器端无法直接获取客户端js的变量值 <script src=""http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.min.js""></script><script type=""text/javascript&qu

代码兼容-JS代码的浏览器兼容问题

问题描述 JS代码的浏览器兼容问题 求大家帮帮忙,我在js代码中写的是 window.onload=function(){setInterval(showtime,1000);} function showtime(){ var current = new Date(); var t = document.getElmentById("time"); t.firstChild.innerText = current.toLocaleString(); } 此代码是在浏览器中实时显示本地

求高手将这段解密的JS转为java代码

问题描述 加密JS代码varbinData=atob(e.target.result);varfileCode=e.target.result;varkey=CryptoJS.enc.Hex.parse('0bf116e3b67f80a8b00b6489b416343cb8647ef1adc17516245967325cd41d2b');variv=CryptoJS.enc.Utf8.parse('zynga.properties');vardecrypted=CryptoJS.AES.decr

移动端js兼容代码禁止放大缩小问题

问题描述 移动端js兼容代码禁止放大缩小问题 <!--移动端版本兼容 --> <script type="text/javascript"> var phoneWidth = parseInt(window.screen.width); var phoneScale = phoneWidth / 640; var ua = navigator.userAgent; if (/Android (d+.d+)/.test(ua)) { var version = p

js 兼容多浏览器的回车和鼠标焦点事件代码(IE6/7/8,firefox,chrome

js 兼容多浏览器的回车和鼠标焦点事件代码(IE6/7/8,firefox,chrome 文本框: 复制代码 代码如下:<input type="text" onkeydown="keydownsearch(event)" /> js代码: 复制代码 代码如下: function keydownsearch(evt) { evt = (evt) ? evt : ((window.event) ? window.event : "")

js兼容多浏览器添加收藏代码

js兼容多浏览器添加收藏代码 */ function addfavor(a){  var url = window.location;  var title = document.title;  var ua = navigator.useragent.tolowercase();  if(ua.indexof("msie 8")>-1){   external.addtofavoritesbar(url,title,'aa');//ie8   }else{    try {  

Java与Node.js的较量--一场史诗之战

纵观整个计算机发展史,1995是疯狂的一年:这一年Java语言诞生,紧跟其后的是JavaScript.后者虽然含有java二字,实际和java并不沾亲带故.Java属于静态编程语言,需要编译:而JavaScript只是一个简单的解释性脚本语言,属于动态语言. 如果经历过早期java发展,我们不难忘记它曾经的空前巅峰:铺天盖地的推广,超大规模的JavaOne会议.很多人都认定,这种新型的编程语言必将不惜一切代价称霸计算机领域.然后这一预测最终证实只是部分准确.而今,安卓应用.企业级服务器应用程序和