在Windows下的Apache 2.4安装casperJS和phantomJS将数据传递给PHP [英] Installing casperJS and phantomJS in WIndows Apache 2.4 to pass data to PHP

查看:315
本文介绍了在Windows下的Apache 2.4安装casperJS和phantomJS将数据传递给PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过单击网站上的运行按钮运行我casperjs脚本。我的本地设置是PHP 5.5.14与Windows7的[正常运行的Apache 2.4;用PHP测试页]。我的问题是:如何这样做,当我执行该脚本其路径被公认为我正确安装casperJS和phantomJS。我需要知道的是怎样的路径是Windows能够使用这样的:传给putenv(PHANTOMJS_EXECUTABLE =的/ usr / local / bin目录/ phantomjs); 。我已经在以下可能的解决方案,但没有人对如何正确安装casperJS和phantomJS使Web服务器识别它们提及:的 CasperJS将数据传回PHP ,<一个href=\"http://stackoverflow.com/questions/23141628/pass-parameter-from-php-to-casperjs-phantomjs\">Pass从PHP参数casperjs / phantomjs ,如何运行casperJS从PHP API 使用casperjs和PHP脚本来保存数据,<一个href=\"http://stackoverflow.com/questions/21563640/php-execution-phantom-js-works-but-casperjs-does-not-work-permission-denied\">php执行幻象JS的作品,但casperjs不工作许可被拒绝

这是我当前的脚本多个用户登录到一个页面,注销,然后再返回多少成功/失败。

  VAR卡斯帕=要求(卡斯帕)。创建()    VAR colorizer =要求('colorizer')创建('Colorizer')。    变种USERNAMES = ['USERNAME1','USERNAME2','USERNAME3','username4','username5'];    变种密码= ['密码1','密码2','password3','password4','password5'];    VAR URL ='http://mywebsitenet.com';    VAR跟踪= {成功:[],失败:[]};    功能登录(用户名,密码){
        casper.then(函数(){
            this.sendKeys('#日志,用户名);
            this.sendKeys('#PWD,密码);
            this.click('#wpmem_login&GT;形式为GT;&字段集GT; div.button_div&GT; input.buttons');
    //执行console.log(用户名+点击了登录按钮!)
        });        casper.waitFor(功能检查(){
            返回this.evaluate(函数(){
                返回的document.getElementById('可湿性粉剂管理员吧-注销');
            });
        },然后函数(){//步执行检查时,()是确定
                this.click('#可湿性粉剂管理员吧,注销&gt;将');
                tracker.Success.push(用户名);
                this.echo(this.fetchText('#可湿性粉剂管理员吧,我的账户&gt;将')+你登录。);
                this.capture(成功_'+用户名+'巴');
        },功能超时(){//执行步骤4,如果检查失败
            tracker.Fail.push(用户名);
            this.echo(警告:+用户名+无法登录。,警告);
            this.capture('失败_'+用户名+'巴');
        });
    };    casper.start(); //空白页    casper.viewport(1024,768);    userNames.forEach(功能(用户名,指数){
        casper.thenOpen(URL); //打开起始页
        登录(用户名,密码[指数]); //计划的步骤
    });    casper.then(函数(){
                this.echo(成功+ tracker.Success.length,INFO);
                this.echo(故障:+ tracker.Fail.length,警告);
                this.echo(JSON.stringify(跟踪));
            });    casper.run(); //开始执行


解决方案

所以,我最终搞清楚至casperJS和phantomJS正确的路径。我把无论是在C中的.exe文件:\\ casperjs \\ BIN,甚至并不需要将它们添加到我的道路,和它的工作非常出色。这是我的index.php,它发送AJAX的PHP页面执行我casperJ脚本(我已经添加到每个成功/失败测试的计数器,以及允许用户选择测试应该如何运行频率):

 &LT;!DOCTYPE HTML&GT;
&LT; HTML和GT;
    &LT; HEAD&GT;
        &LT;链接rel =stylesheet属性HREF =style.css文件类型=文/ CSS媒体=屏幕投影/&GT;
        &LT;链接rel =快捷方式图标类型=图像/ ICOHREF =favicon_jdoe.png/&GT;
        &LT;脚本SRC =jQuery的-2.1.1.min.js类型=文/ JavaScript的&GT;&LT; / SCRIPT&GT;
        &LT;脚本类型=文/ JavaScript的LANGUAGE =JavaScript的SRC =jquery.dropdownPlain.js&GT;&LT; / SCRIPT&GT;
        &LT;标题&GT; CasperJS自动化测试单元&LT; /标题&GT;
    &LT; /头&GT;
    &LT;中心及GT;
    &LT;身体GT;
    &LT; D​​IV ID =日程地址搜索Maincontent&GT;
&LT; P&GT;欢迎CasperJS自动化测试单元&LT; / P&GT;
&LT; BR&GT;
  &LT;按钮ID =button_AJAX&gt;运行CasperJS&LT; /按钮&GT;
  &LT;按钮ID =button_STOP的onclick =myStopFunction()的风格=显示:无&GT;停止CasperJS&LT; /按钮&GT;
    &LT; / DIV&GT;&所述p为H.;
&LT;选择ID =多&GT;
&LT;期权价值=1大于1分钟&lt; /选项&GT;
&LT;期权价值=2→2分钟&lt; /选项&GT;
&LT;期权价值=5大于5分钟&lt; /选项&GT;
&LT;期权价值=10大于10分钟&lt; /选项&GT;
&LT;期权价值=30选​​择=选择了大于30分钟&lt; /选项&GT;
&LT;期权价值=60&GT; 1.5小时&LT; /选项&GT;
&LT;期权价值=360→6时及LT; /选项&GT;
&LT;期权价值=720&GT 12时及LT; /选项&GT;
&LT;期权价值=1440→1白天&LT; /选项&GT;
&LT; /选择&GT;
&所述; / P&GT;&所述p为H.;
    &LT; D​​IV CLASS =中心&GT;
    &LT; D​​IV的风格=浮动:左;保证金右:20px的&GT;
        &LT; D​​IV的风格=浮动:左&GT;成功计数:其中; / DIV&GT;
        &LT; D​​IV ID =succcount的风格=浮动:左&GT; 0℃; / DIV&GT;
    &LT; / DIV&GT;
    &LT; D​​IV的风格=浮动:左&GT;
        &LT; D​​IV的风格=浮动:左&GT;失败计数:LT; / DIV&GT;
        &LT; D​​IV ID =故障计数的风格=浮动:左&GT; 0℃; / DIV&GT;
    &LT; / DIV&GT;
    &LT; / DIV&GT;
&所述; / P&GT;    &LT; BR&GT;    &LT; BR&GT;
    &LT; D​​IV ID =加载&GT;&LT; / DIV&GT;
&LT;脚本类型=文/ JavaScript的&GT;    变种succcount = 0;
    VAR故障计数= 0;    $('#button_AJAX')。点击(函数executecasperJS(){
       $('#装载)HTML。('&LT; IMG SRC =rays.gif&GT;&LT; BR&GT;&LT; I&GT; Web收割正在进行中,请等待测试结果&​​LT; / I&GT;'); //加载图像
            $阿贾克斯({//运行Ajax请求
            键入:GET,
            数据类型:TEXT,
            网址:casperJS.php
            成功:功能(数据){
                    $('#装载)HTML(数据)。                    如果(data.indexOf('失败:0!)== -1){
                        succcount ++;
                    }其他{
                        故障计数++;
                    }
                    $('#succcount')HTML(succcount);
                    $('#故障计数)HTML(故障计数);
            }
        });多= $(#multi选项:选择).VAL();
的console.log(多=+多);超时= setTimeout的(executecasperJS,多* 60000); // 1分钟== 60000
});
    $(#button_AJAX)点击(函数(){$(#button_AJAX)文本(CasperJS实行);});
    $(#button_STOP)点击(函数(){$(#button_AJAX),文字(运行CasperJS);});
    功能myStopFunction(){
        clearTimeout(超时);
    }    $(#button_AJAX)。点击(函数(){
       $(#button_STOP)显示()。
     });     $(#button_STOP)。点击(函数(){
        $(#button_STOP),隐藏()。
      });&LT; / SCRIPT&GT;
&LT; / DIV&GT;
    &LT; D​​IV ID =页面换行&GT;
            &LT; UL类=下拉菜单&GT;
            &LT;立GT;&LT; A HREF =#&GT; CasperJS日志&LT; / A&GT;
                &LT; UL类=sub_menu&GT;
                     &LT;立GT;&LT; A HREF =casperjs_log.txt目标=_空白&GT;测试日志与LT; / A&GT;&LT; /李&GT;
                     &LT;立GT;&LT; A HREF =casperjs_error.txt目标=_空白&GT;错误日志&LT; / A&GT;&LT; /李&GT;
        &LT; / UL&GT;
    &LT; / DIV&GT;
&LT; /中心及GT;
    &LT; /身体GT;
&LT; / HTML&GT;

和这里的 casperJS.php ;这如果发生故障发送电子邮件:

 &LT; PHP或者set_time_limit(3600);date_default_timezone_set(美国/纽约');
$日期=日期('M / D / Y H:我:是个',时间());
$ TIME_START = microtime中(真);
$输出= EXEC(C:\\ casperjs \\ BIN \\ casperjs casperJScript.js);
    如果(strpos($输出,'失败:0')=== FALSE){
        require_once('PHPMailer_5.2.4 / class.phpmailer.php');
        $邮件=新的PHPMailer();
        $ MAIL-GT&; IsSMTP();
        $ MAIL-GT&; SMTPDebug = 1;
        $ MAIL-GT&; SMTPAUTH = TRUE;
        $ MAIL-GT&; SMTPSecure =SSL;
        $ MAIL-GT&; HOST =smtp.gmail.com;
        $ MAIL-GT&;港口= 465;
        $ MAIL-GT&; IsHTML(真);
        $ MAIL-GT&;用户名=email@host.com;
        $ MAIL-GT&;密码=密码;
        $ MAIL-GT&; SetFrom('email@host.co');
        $ MAIL-&GT; AddReplyTo(email@host.co);
        $ MAIL-GT&;学科=casperJS:服务器发生故障在$日期;
        $ MAIL-GT&;身体=该casperJS检测单位已经拿起了服务器故障:$输出
        $ MAIL-&GT; AddAddress(email@host.co);
        如果($ MAIL-GT&;!发送()){
        //回声梅勒错误:。 $ MAIL-GT&; ERRORINFO;
        }其他{
        //回声发生错误和故障的邮件已发送。
        呼应'&LT;跨度风格=COLOR:#FF0000&gt;一种错误发生;它被记录和电子邮件通知已发送&LT; / SPAN&GT;';
        $ USERIP = $ _ SERVER ['REMOTE_ADDR'];
        $文件='casperjs_error.txt';
        $ oldContents =的file_get_contents($文件);
        $ FR =的fopen($文件,'W');
        $ TXT =错误日志:$输出的要求:$ USERIP在$日期。 。 PHP_EOL。 PHP_EOL;
        FWRITE($ FR,$ TXT);
        FWRITE($ FR,$ oldContents);
        FCLOSE($ FR);
        回声&LT; BR /&gt;中;
        回声&LT; BR /&gt;中;
        }
    }
    回声测试结果:$输出;
    $ USERIP = $ _ SERVER ['REMOTE_ADDR'];
    $ TIME_END = microtime中(真);
    $时间= $ TIME_END - $ TIME_START;
    回声&LT; BR /&gt;中;
    回声&LT; BR /&gt;中;
    回声最后测试在$时间秒\\ n $上完成日期;
    $文件='casperjs_log.txt';
    $ oldContents =的file_get_contents($文件);
    $ FR =的fopen($文件,'W');
    $ TXT =日志:$输出测试在$时间秒内完成\\ n $上按日期请求:$ USERIP。 PHP_EOL。 PHP_EOL;
    FWRITE($ FR,$ TXT);
    FWRITE($ FR,$ oldContents);
    FCLOSE($ FR);
?&GT;

I am attempting to run my casperjs script by clicking a Run button in a website. My local set up is PHP 5.5.14 with Apache 2.4 on Windows7 [properly running; tested with php page]; and my question is: how do I properly install casperJS and phantomJS so that its PATH is recognized when I execute the script. I need to know what the path is in Windows to be able to use this: putenv("PHANTOMJS_EXECUTABLE=/usr/local/bin/phantomjs");. I have gone over the following possible solutions but none of them mention on how to properly install casperJS and phantomJS for the web server to recognize them: CasperJS passing data back to PHP, Pass parameter from php to casperjs/phantomjs, How to run casperJS script from php API, Using casperjs and PHP to save data, php execution phantom js works but casperjs does not work permission denied

This is my current script for multiple users to log-in to a page, log-out and then return how many successes/failures.

    var casper = require('casper').create()

    var colorizer = require('colorizer').create('Colorizer');

    var userNames = ['username1','username2','username3','username4', 'username5'];

    var passWords = ['password1','password2','password3','password4', 'password5'];

    var url = 'http://mywebsitenet.com';

    var tracker = {Success: [], Fail: []};

    function login(username, password) {
        casper.then(function () {
            this.sendKeys('#log', username);
            this.sendKeys('#pwd', password);
            this.click('#wpmem_login > form > fieldset > div.button_div > input.buttons');
    //      console.log(username + " has clicked the Log In button!")
        });

        casper.waitFor(function check() {
            return this.evaluate(function() {
                return document.getElementById('wp-admin-bar-logout');
            });
        }, function then() {    // step to execute when check() is ok
                this.click('#wp-admin-bar-logout > a'); 
                tracker.Success.push(username);
                this.echo(this.fetchText('#wp-admin-bar-my-account > a') + " you logged in.");
                this.capture('Success_'+username+'.png');       
        }, function timeout() { // step to execute if check has failed
            tracker.Fail.push(username);
            this.echo("Warning: " + username + " could not be logged in.", "WARNING");
            this.capture('Fail_'+username+'.png');
        });    
    };

    casper.start(); // empty page

    casper.viewport(1024, 768);

    userNames.forEach(function(username, index){
        casper.thenOpen(url); // open the start page
        login(username, passWords[index]); // schedule the steps
    });

    casper.then(function () {
                this.echo("Success: " + tracker.Success.length, "INFO");
                this.echo("Fail: " + tracker.Fail.length, "WARNING");
                this.echo(JSON.stringify(tracker));
            });

    casper.run(); // begin the execution

解决方案

So I ended up figuring out the proper path to casperJS and phantomJS. I placed both of the .exe in C:\casperjs\bin and did not even need to add them to my PATH, and it worked very well. This is my index.php, which sends AJAX for a php page executing my casperJ-script (I have added a counter for each successful/failed test, as well as allowed the user to select how frequently the test should run):

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="style.css" type="text/css" media="screen, projection"/>
        <link rel="shortcut icon" type="image/ico" href="favicon_jdoe.png" />
        <script src="jquery-2.1.1.min.js" type="text/javascript"></script>
        <script type="text/javascript" language="javascript" src="jquery.dropdownPlain.js"></script>
        <title>CasperJS Automated Testing Unit</title>
    </head>
    <center>
    <body>
    <div id="mainContent">
<p>Welcome to the CasperJS Automated Testing Unit</p>
<br>
  <button id="button_AJAX">Run CasperJS</button>
  <button id="button_STOP" onclick="myStopFunction()" style="display: none">Stop CasperJS</button>
    </div>

<p>
<select id="multi">
<option value="1">1 min</option>
<option value="2">2 min</option>
<option value="5">5 min</option>
<option value="10">10 min</option>
<option value="30" selected="selected">30 min</option>
<option value="60">1 hour</option>
<option value="360">6 hours</option>
<option value="720">12 hours</option>
<option value="1440">1 day</option>
</select>
</p>

<p>
    <div class="centered">
    <div style="float:left; margin-right:20px">
        <div style="float:left">Success count:</div>
        <div id="succcount" style="float:left">0</div> 
    </div>
    <div style="float:left">
        <div style="float:left">Fail count:</div>
        <div id="failcount" style="float:left">0</div>
    </div>
    </div>
</p>

    <br>

    <br>
    <div id="loading"></div>
<script type="text/javascript">

    var succcount = 0;
    var failcount = 0;

    $('#button_AJAX').click(function executecasperJS() {
       $('#loading').html('<img src="rays.gif"><br><i>Web harvesting in progress; please wait for test results.</i>');  // Loading image
            $.ajax({    // Run ajax request
            type: "GET",
            dataType: "text",
            url: "casperJS.php",
            success: function (data) {        
                    $('#loading').html(data);

                    if( data.indexOf('Fail: 0') !== -1 ) {
                        succcount++;
                    } else {
                        failcount++;
                    }
                    $('#succcount').html(succcount);
                    $('#failcount').html(failcount);
            }   
        });

multi = $( "#multi option:selected" ).val();
console.log("multi="+multi);        

timeout = setTimeout(executecasperJS,multi*60000); //1 min == 60000 
});
    $("#button_AJAX").click(function() {$("#button_AJAX").text("CasperJS Executed");});
    $("#button_STOP").click(function() {$("#button_AJAX").text("Run CasperJS");});
    function myStopFunction() {
        clearTimeout(timeout);
    } 

    $("#button_AJAX").click(function(){
       $("#button_STOP").show();
     });

     $("#button_STOP").click(function(){
        $("#button_STOP").hide();
      });

</script>
</div>
    <div id="page-wrap">
            <ul class="dropdown"> 
            <li><a href="#">CasperJS Logs</a>
                <ul class="sub_menu">
                     <li><a href="casperjs_log.txt" target="_blank">Testing Log</a></li>
                     <li><a href="casperjs_error.txt" target="_blank">Error Log</a></li>
        </ul>
    </div>
</center>
    </body>
</html> 

and here is the casperJS.php; which sends out an email if a failure occurs:

<?php

set_time_limit(3600);

date_default_timezone_set('America/New_York');
$date = date('m/d/Y h:i:s a', time());
$time_start = microtime(true);
$output = exec("C:\casperjs\bin\casperjs casperJScript.js");
    if (strpos($output, 'Fail: 0') === FALSE) {
        require_once('PHPMailer_5.2.4/class.phpmailer.php');
        $mail             = new PHPMailer();
        $mail->IsSMTP();     
        $mail->SMTPDebug  = 1;                   
        $mail->SMTPAuth   = true;                  
        $mail->SMTPSecure = "ssl";                
        $mail->Host       = "smtp.gmail.com";      
        $mail->Port       = 465;                   
        $mail->IsHTML(true);     
        $mail->Username   = "email@host.com";  
        $mail->Password   = "password";            
        $mail->SetFrom('email@host.co');
        $mail->AddReplyTo("email@host.co");
        $mail->Subject    = "casperJS: Server failure occured on $date";
        $mail->Body    = "The casperJS testing unit has picked up a server fault: $output
        $mail->AddAddress("email@host.co");
        if(!$mail->Send()) {
        //echo "Mailer Error: " . $mail->ErrorInfo;
        } else {
        //  echo "An error has occured and an email with the fault has been sent.";
        echo '<span style="color:#FF0000">An error has occured; it was logged and an email notification has been sent.</span>';
        $userip = $_SERVER['REMOTE_ADDR'];
        $file = 'casperjs_error.txt';
        $oldContents = file_get_contents($file);
        $fr = fopen($file, 'w');
        $txt = "ERROR log: $output. Requested by: $userip on $date." . PHP_EOL . PHP_EOL ;
        fwrite($fr, $txt);
        fwrite($fr, $oldContents);
        fclose($fr);    
        echo "<br />";
        echo "<br />";
        }
    }
    echo "Test Results: $output";
    $userip = $_SERVER['REMOTE_ADDR'];
    $time_end = microtime(true);
    $time = $time_end - $time_start;
    echo "<br />";
    echo "<br />";
    echo "Last test completed in $time seconds\n on $date";
    $file = 'casperjs_log.txt';
    $oldContents = file_get_contents($file);
    $fr = fopen($file, 'w');
    $txt = "Log: $output. Test completed in $time seconds\n on $date. Requested by: $userip" . PHP_EOL . PHP_EOL ;
    fwrite($fr, $txt);
    fwrite($fr, $oldContents);
    fclose($fr);        
?>

这篇关于在Windows下的Apache 2.4安装casperJS和phantomJS将数据传递给PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆