如何通过提交表单登录CasperJS。我搜索谷歌并没有找到任何关于它的好例子。
答案 0 :(得分:52)
您需要使用Casper fill()功能。
以下是登录Facebook并在登录后打印出您的姓名的示例。请注意,您需要输入用户名和密码:
var casper = require('casper').create({
verbose: true,
logLevel: 'debug',
pageSettings: {
loadImages: false, // The WebPage instance used by Casper will
loadPlugins: false, // use these settings
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4'
}
});
// print out all the messages in the headless browser context
casper.on('remote.message', function(msg) {
this.echo('remote message caught: ' + msg);
});
// print out all the messages in the headless browser context
casper.on("page.error", function(msg, trace) {
this.echo("Page Error: " + msg, "ERROR");
});
var url = 'http://www.facebook.com/';
casper.start(url, function() {
console.log("page loaded");
this.test.assertExists('form#login_form', 'form is found');
this.fill('form#login_form', {
email: '**<put your email here>**',
pass: '**<put your password here>**'
}, true);
});
casper.thenEvaluate(function(){
console.log("Page Title " + document.title);
console.log("Your name is " + document.querySelector('.headerTinymanName').textContent );
});
casper.run();
答案 1 :(得分:7)
以下是Ngo Hung的代码略有修改版本。用户名的选择器已关闭,userAgent的分配也是如此:
var casper = require('casper').create({
verbose: true,
logLevel: 'debug',
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22',
pageSettings: {
loadImages: false, // The WebPage instance used by Casper will
loadPlugins: false // use these settings
}
});
// print out all the messages in the headless browser context
casper.on('remote.message', function(msg) {
this.echo('remote message caught: ' + msg);
});
// print out all the messages in the headless browser context
casper.on("page.error", function(msg, trace) {
this.echo("Page Error: " + msg, "ERROR");
});
var url = 'http://www.facebook.com/';
casper.start(url, function() {
console.log("page loaded");
this.test.assertExists('form#login_form', 'form is found');
this.fill('form#login_form', {
email: '**<put your email here>**',
pass: '**<put your password here>**'
}, true);
});
casper.thenEvaluate(function(){
console.log("Page Title " + document.title);
console.log("Your name is " + document.querySelector(".fbxWelcomeBoxName").innerHTML);
});
casper.run();
更新:我建议其他人使用他们自己的网站,或者至少不是facebook.com,如果他们计划进行大量测试的话。 Facebook可以告诉我,我一直在尝试登录,并开始向我发送电子邮件,让我通过短信确认我的帐户。