问题
I have a casperjs problem. I can't extract value from an id with javascript.
I am opening google, searching a term, and i want to get the value from the searchbox by 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();
回答1:
There are two possibilities to get the value of an input on the page.
You can either register to remote.message event and log it on the page
// 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); });or return the string from the page context
// inside of the step var inputValue = casper.evaluate(function () { document.getElementById('gbqfq').value = "samearga"; return document.getElementById('gbqfq').value; }); casper.echo(inputValue);
You have to keep in mind what this means. Inside of the page context (inside of casper.evaluate) this refers to window, but window doesn't have an echo function. Page and casper contexts are distinct from one another (sandboxed) and you can't just use all variables. More in the docs.
来源:https://stackoverflow.com/questions/27150647/how-can-i-extract-an-input-value-by-id-with-casperjs