阅读了这个问题后,我设置了一个 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 调用(最外面的那个),我会得到一个错误ReferenceError: Can't find variable: $
此外,如果您想以这种方式一个接一个地测试大量按钮单击,那么您最终将得到难以管理的高度嵌套的函数调用。
我觉得我真的很困惑,并且没有以正确的方式做事。有人可以解释在 PhantomJS 中单击链接、提交表单数据和评估结果页面的正确方法吗?