单击按钮并在PhantomJS中评估结果页面

时间:2013-11-07 17:40:12

标签: javascript jquery forms phantomjs

阅读this question后,我设置了onLoadFinished函数,在表单数据提交后处理页面:

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

page.open("http://www.mysite.com/login", function (status) {
  page.includeJs('jquery-1.10.2.min.js', function () {

    //Setup function to handle receiving the response after we click the button
    page.onLoadFinished = function (response) {
      page.includeJs('jquery-1.10.2.min.js', function () {
        var out = page.evaluate(function () {
          //For simplicity, let's say the resulting page contains only one div
          //with the output we want to test.
          return $("div").html();
        });

        //If the term 'Username or Password Incorrect' is on the page, then that
        //means the login failed.
        if(out.search('Username or Password Incorrect') !== -1) {
          console.log("Failed to login when it should have worked.");
        } else {
          console.log("Login succeeded.");
        }
        phantom.exit();
      });
    };

    //This is where we actually load the page for the first time and submit the
    //form data
    page.evaluate(function () {
      $("input[name=username]").val("Sam");
      $("input[name=password]").val("password");
      $("button[type=submit]").click();
    });
  });
});

现在,这段代码有效,但在我看来,我不应该多次包含相同的JS文件。但如果我只包含第一个includeJs调用(outtermost),我会收到错误ReferenceError: Can't find variable: $

另外,如果你想以这种方式一个接一个地测试很多按钮点击,那么你最终将会遇到难以管理的大量嵌套函数调用。

我觉得我真的很困惑,而且没有按照正确的方式做事。有人可以解释在PhantomJS中点击链接,提交表单数据和评估结果页面的正确方法吗?

0 个答案:

没有答案