我遇到了 casperjs 问题。我无法使用 JavaScript 从 id 中提取值。
我正在打开谷歌,搜索一个术语,我想通过 id 从搜索框中获取值。
var casper = require('casper').create({
verbose: true,
logLevel: "info"
});
var mouse = require("mouse").create(casper);
var x = require('casper').selectXPath;
var webPage = require('webpage');
var page = webPage.create();
casper.userAgent('Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36')
casper.start("http://www.google.com/ncr", function () {
this.echo(this.getTitle());
}).viewport(1366, 768);
//casper.then(function() {
//this.sendKeys('#gbqfq', 'Duke');
//this.click('#gbqfsa');
//});
casper.waitForSelector(x('//*[@id="gbqfq"]'), function () {
this.evaluate(function () {
document.getElementById('gbqfq').value = "samearga";
this.echo(this.document.getElementById('gbqfq').value);
});
console.log("\nEXISTA SELECTORUL!!! -> document.getElementById('gbqfq').value\n");
});
casper.waitForSelector(x('//*[@id="gbqfq"]'), function () {
this.evaluate(function () {
document.forms[0].submit();
});
console.log("\nSUBMITING!!!\n");
});
casper.wait(4000, function () {
console.log("\nFAC POZA\n");
casper.capture('caca.png');
});
casper.run();
最佳答案
有两种方法可以获取页面上输入的值。
您可以注册到
remote.message
事件并将其记录在页面上// at the beginning of the script casper.on("remote.message", function(msg){ this.echo("remote> " + msg); }); // inside of the step casper.evaluate(function () { document.getElementById('gbqfq').value = "samearga"; console.log(document.getElementById('gbqfq').value); });
或从页面上下文返回字符串
// inside of the step var inputValue = casper.evaluate(function () { document.getElementById('gbqfq').value = "samearga"; return document.getElementById('gbqfq').value; }); casper.echo(inputValue);
您必须记住这
的含义。页面上下文内部(casper.evaluate
内部)this
引用 window
,但 window
不引用有一个echo
功能。页面和 casper 上下文彼此不同(沙盒),您不能只使用所有变量。更多内容请参见docs .
关于javascript - 如何使用 CasperJS 通过 id 提取输入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27150647/