Reputation: 19896
I must have lost my mind on this but why it didn't print out "1: Google Search"
and "2: Google Search"
? Basically: how do I get a variable within this.evaluate and use it in the rest of casper.js scope?
var casper = require("casper").create();
var buttonText;
casper.start("http://google.com");
casper.then(function() {
buttonText = this.evaluate(function () {
var myTxt = document.querySelector('#gbqfsa').innerText;
console.log('1: ' + myTxt);
return myTxt;
});
});
casper.then(function() {
this.echo('2: ' + buttonText);
});
casper.on('remote.message', function(msg) {
this.echo('remote message caught: ' + msg);
});
casper.run();
I am using these libraries here:
https://github.com/ariya/phantomjs
http://casperjs.org/index.html
Upvotes: 4
Views: 6312
Reputation: 11414
The problem is that Google seems to be serving different versions when browsed with different user agents, for some very obscure reason. I'm suspecting heavy browser/user agent sniffing.
In our case, playing with Casper.debugHTML()
shows that the code doesn't contain the button matching the #gbqfsa
selector (while Chrome shows one); instead a standard submit <input name="btnG">
is there.
So here's your script using the actual selector for the button:
var casper = require("casper").create();
var buttonText;
casper.start("http://google.com/", function() {
buttonText = this.evaluate(function () {
var myTxt = document.querySelector('input[name="btnG"]').getAttribute('value');
__utils__.echo('1: ' + myTxt);
return myTxt;
});
this.echo('2: ' + buttonText);
});
casper.run();
Just an idea, try to use Casper.userAgent()
to set the UA to something more common, eg. a recent chrome version.
PS: also notice the use of __utils__.echo()
to print stuff directly from within evaluate()
.
Edit: It works by setting a common UA:
casper.start();
casper.userAgent("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.204 Safari/534.16");
casper.thenOpen('http://google.com/', function() {
this.test.assertExists('#gbqfsa'); // PASS
});
casper.run(function() {
this.test.done();
});
Upvotes: 9
Reputation: 880
Did you try this for debugging?
casper.on('remote.message', function(message) {
this.echo('remote console message: ' + message);
});
Have a look at Events & filters - hooking & altering the CasperJS environment at runtime.
Upvotes: 0
Reputation: 19896
I think there is serious issue with casper.js or phantom.js about debugging within evaluate(). If I replace below line, it works
var myTxt = document.querySelector('.gbts').innerHTML;
The question is: how to debug when there are javascript errors within evaluate()? There is no way to know...
Upvotes: 0