使用nodejs + phantomjs自动登录+发布到论坛

时间:2015-11-15 04:14:16

标签: node.js phantomjs yetanotherforum

我正在尝试使用node-phantom自动登录论坛(另一个论坛,测试论坛:http://testforum.yetanotherforum.net/)。

这是我的代码:

/**
 * Yet Another Forum Object
 *
 *
 */
var yaf = function() {}; //

module.exports = new yaf();


var phantom = require('node-phantom');

//var sleep = require('sleep');


var configTestForum = {
  loginUrl: "http://testforum.yetanotherforum.net/login",
  loginFormDetail: {
    usernameBox: 'forum_ctl03_Login1_UserName', // dom element ID
    passwordBox: 'forum_ctl03_Login1_Password',
    submitButton: 'forum_ctl03_Login1_LoginButton'
  },
  loginInfo: {
    username: 'testbot',
    password: 'testbot123'
  }
};

var config = configTestForum;


// program logic
yaf.prototype.login = function(username, password, cb) {

  var steps = [];
  var testindex = 0;
  var loadInProgress = false; //This is set to true when a page is still loading

  /*********SETTINGS*********************/


  phantom.create(function(error, ph) {
    ph.createPage(function(err, page) {


      page.set('settings', {
        userAgent: "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0",
        javascriptEnabled: true,
        loadImages: false,
      });

      phantom.cookiesEnabled = true;
      phantom.javascriptEnabled = true;
      /*********SETTINGS END*****************/

      console.log('All settings loaded, start with execution');

      /**********DEFINE STEPS THAT FANTOM SHOULD DO***********************/
      steps = [

        //Step 1 - Open Amazon home page
        function() {
          console.log('Step 1 - Open Login Page');

          page.open(config.loginUrl, function(status) {

          });
        },
        function() {
          console.log('Step 2 - Populate and submit the login form');


          var submitForm = function(config) {

            console.log('Form Submit 1 ( putting login )');
            document.getElementById(config.loginFormDetail.usernameBox).value = config.loginInfo.username;
            console.log('Form Submit 2 ( putting pass )');

            //jQuery('#' + config.loginFormDetail.passwordBox).val(config.loginInfo.password);
            //jQuery('#' + config.loginFormDetail.usernameBox).val(config.loginInfo.password);

            document.getElementById(config.loginFormDetail.passwordBox).value = config.loginInfo.password;
            console.log('Form Submit 3 ( clicking button ) ');
            document.getElementById(config.loginFormDetail.submitButton).click();

            //var clickElement = function (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);
            //    console.log('dispatched!');
            //};

            //document.getElementById(config.loginFormDetail.submitButton).click();
            //clickElement(jQuery("#forum_ctl03_Login1_LoginButton")[0]);

            //
            //var form = document.getElementById('form1');
            ////var list = function(object) {
            ////    for(var key in object) {
            ////        console.log(key);
            ////    }
            ////};
            ////list(form);
            //
            //
            //// jQuery('#form1').submit();
            //
            //form.submit();
            //
            //document.forms[0].submit();

            //HTMLFormElement.prototype.submit.call(jQuery('form')[0]);

            console.log('Form Has Been Submitted <-----------------');
          };

          var subittedForm = function(err, retVal) {
            console.log('Form Submit error : ' + err);
            console.log('Form Submit returned : ' + retVal);
          };


          //page.evaluateJavaScript(jsCode);
          page.evaluate(submitForm, subittedForm, config);


        },
        //Step 3 - wait for submit form to finish loading..
        function() {
          //sleep.sleep(5);
          console.log("Step 3 - wait for submit form to finish loading..");
          //sleep.sleep(3);
          page.render('loginComplete.png');
          page.get('cookies', function(err, cookies) {
            //   console.log(cookies);
          });

          page.evaluate(function() {
            console.log(document.URL);
          });


        },
        function() {
          console.log('Exiting');
        }
      ];
      /**********END STEPS THAT FANTOM SHOULD DO***********************/

      //Execute steps one by one
      interval = setInterval(executeRequestsStepByStep, 500);

      function executeRequestsStepByStep() {
        if (loadInProgress == false && typeof steps[testindex] == "function") {
          //console.log("step " + (testindex + 1));
          steps[testindex]();
          testindex++;
        }
        if (typeof steps[testindex] != "function") {
          console.log("test complete!");
          ph.exit();
          // cb(ph);
          cb('done');
        }
      }


      page.onLoadStarted = function() {
        loadInProgress = true;
        console.log('Loading started');
      };
      page.onLoadFinished = function() {
        loadInProgress = false;
        console.log('Loading finished');
      };
      page.onConsoleMessage = function(msg) {
        console.log(msg);
      };
      page.onError = function(msg, trace) {
        var msgStack = ['ERROR: ' + msg];

        if (trace && trace.length) {
          msgStack.push('TRACE:');
          trace.forEach(function(t) {
            msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function+'")' : ''));
          });
        }

        console.error('\n' + msgStack.join('\n'));
      };
      page.onResourceError = function(resourceError) {
        console.error('Unable to load resource (#' + resourceError.id + ' URL:' + resourceError.url + ')');
        console.error('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
      };
      page.onResourceTimeout = function(msg) {
        console.error('onResourceTimeout!!>' + msg);
      };
      page.onAlert = function(msg) {
        console.error('onAlert!!> ' + msg);
      };


    });
  });


  //  var page = webPage.create();

};

代码输出为:

Step 1 - Open Login Page
Loading started
Loading finished
Step 2 - Populate and submit the login form
Form Submit 1(putting login)
Form Submit 2(putting pass)
Form Submit 3(clicking button)
Form Has Been Submitted < -----------------
  Form Submit error: null
Form Submit returned: null
Unable to load resource(#14 URL:http://testforum.yetanotherforum.net/login?g= login &= )
Error code: 5.Description: Operation canceled

ERROR: TypeError: 'undefined'
is not an object(evaluating 'Sys.WebForms.Res.PRM_TimeoutError'), [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object]
Step 3 - wait
for submit form to finish loading..
http: //testforum.yetanotherforum.net/login
  Exiting
test complete!
  done
Option client store expiration is not valid.Please refer to the README.

Process finished with exit code 0

它试图做的是:

  1. 打开登录页面:http://testforum.yetanotherforum.net/login?returnurl=%2fcategory%2f1-Test-Category
  2. 尝试使用登录名/密码登录,然后单击按钮。
  3. 截取屏幕截图并检索Cookie(包含身份验证数据)
  4. 目前它已经陷入第2步。它可以填充登录和密码框,但没有任何点击或提交表单工作。基本上它卡住了如下所示:

      

         

    (正如您所看到的,正确填写了登录名/密码)。

    通过查看我的代码中的第2步(步骤2 - 填充并提交登录表单),您是否注意到任何明显的事情?或者我在页面设置中做错了什么?

0 个答案:

没有答案