HP.*_*HP. 4 javascript scope webkit phantomjs casperjs
我一定是失去了我的脑海里就这一点,但它为什么没有打印出来"1: Google Search",并"2: Google Search"?基本上:如何在this.evaluate中获取变量并在casper.js范围的其余部分中使用它?
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();
Run Code Online (Sandbox Code Playgroud)
我在这里使用这些库:
问题在于谷歌似乎在使用不同的用户代理浏览时提供不同的版本,原因有些晦涩难懂.我怀疑沉重的浏览器/用户代理嗅探.
在我们的例子中,使用Casper.debugHTML()显示代码不包含与#gbqfsa选择器匹配的按钮(而Chrome显示一个); 相反,标准提交<input name="btnG">就在那里.
所以这是你的脚本使用按钮的实际选择器:
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();
Run Code Online (Sandbox Code Playgroud)
只是一个想法,尝试使用Casper.userAgent()UA设置更常见的东西,例如.最新的chrome版本.
PS:还注意到__utils__.echo()直接从内部打印东西的用法evaluate().
编辑:它通过设置一个共同的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();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6252 次 |
| 最近记录: |