PhantomJs登录测试

Login Test with PhantomJs

本文关键字:测试 登录 PhantomJs      更新时间:2023-09-26

我的phantom Js代码有问题,如下所示,我有代码来测试我的朋友web服务器(使用节点Js制作)。事实上,它看起来简单而完美。

var page = require('webpage').create();
var address   = "http://localhost:3333";
// Route "console.log()" calls from within the Page context to the 
// main Phantom context (i.e. current "this")
page.onConsoleMessage = function(msg) {
  console.log("Console.log: ", msg);
};
page.onAlert = function(msg) {
  console.log("Alert:", msg);
};
page.open(address, function (s) {
    page.evaluate(function () {
  function click(el){
      var ev = document.createEvent("MouseEvent");
      ev.initMouseEvent(
      "click",
      true /* bubble */,
      true /* cancelable */,
      window, null,
      0, 0, 0, 0, /* coordinates */
      false, false, false, false, /* modifier keys */
      0 /*left*/, null
      );
      el.dispatchEvent(ev);
  }
  document.getElementById('username').value = 'MyName';
  document.getElementById('password').value = 'MyWord';
  click(document.querySelector('input[type=submit]'));
    });
    page.onNavigationRequested = function() {
  // console.log("Moved", JSON.stringify(arguments))
  // to check whether send or not
  page.render("printscreen" + ".png");
    };
    setTimeout(function(){
  page.render("nextprintscreen" + ".png");
        phantom.exit();
    }, 3000);
});

但是

当我申报
var userName = 'MyName';
var passWord = 'MyWord';
然后将其放置在
下方var address = "http://localhost:3333";
和交换
document.getElementById('username').value = 'MyName';
document.getElementById('password').value = 'MyWord';

document.getElementById('username').value = userName;
document.getElementById('password').value = passWord;

它从我的朋友网络服务器返回CCD_ 8。你能帮我弄清楚为什么会这样吗。这是我的第一个"javascript世界"代码。

我已经阅读了这个问题和另一个变体,然后建议

但这只会让我更加困惑。

谢谢,
Ahmad

问题是page.evaluate()是沙盒的,因此无法访问幻影脚本的变量。

由于PhantomJS 1.6,JSON可序列化参数可以传递给page.evaluate()。evaluate函数的参数和返回值必须是简单基元对象。但是,对象可以通过JSON进行序列化。

您可以将代码更改为:

page.evaluate(function (login, pwd) {
     ...
     document.getElementById('username').value = login;
     document.getElementById('password').value = pwd;
     ...
}, userName , passWord );