如何通过提交表单使用 CasperJS 登录。我搜索了谷歌并没有找到任何关于它的好例子。
user1647411
问问题
36641 次
2 回答
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();
于 2012-11-14T10:05:55.773 回答
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 可以告诉我,我一遍又一遍地尝试登录,开始给我发电子邮件,让我用 SMS 确认我的帐户。
于 2013-06-03T21:46:14.297 回答