您好我正在学习casperjs。但是我遇到了代码问题
document.getElementsByClassName('darkest dps64 profiles-show fls45 links _a _jm')[0].getElementsByTagName('a').length;
当我运行脚本时,它根本不起作用。但是,当我在Mozilla / chrome控制台中编写时,它可以工作。在控制台中,它给了我“5”,正如我预期的那样但在cmd上它给了我
TypeError:'undefined is not an object <evaluating 'document.getElementsByClassName('darkest dps64 profiles-show fls45 links _a _jm')[0].getElementsByTagName('a').length;
我知道undefined意味着它无法在页面上找到它,但是当我拍摄截图时,它显示它在右侧页面上。所以必须找到?但不幸的是,它没有。我的代码在下面。谢谢你的帮助:)
phantom.casperPath = 'C:/casperjs';
phantom.injectJs(phantom.casperPath + '/bin/bootstrap.js');
var casper = require('casper').create({
pageSettings: {
loadImages: false,//The script is much faster when this field is set to false
loadPlugins: false,
userAgent: 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'
}
});
casper.start().thenOpen("https://angel.co/mike_greenfield?utm_source=people", function () {
console.log("site opened");
});
casper.then(function () {
this.capture('pic.png');
});
casper.then(function () {
var howmanylinks= document.getElementsByClassName('darkest dps64 profiles-show fls45 links _a _jm')[0].getElementsByTagName('a').length;
console.log(howmanylinks);
});
casper.then(function () {
casper.exit();
});
casper.run();
答案 0 :(得分:0)
只能在casper.evaluate()
内访问DOM。虽然document
可以在外面使用,但它没有做任何事情:
casper.then(function () {
var howmanylinks = this.evaluate(function(){
return document.getElementsByClassName('darkest dps64 profiles-show fls45 links _a _jm')[0].getElementsByTagName('a').length;
});
console.log(howmanylinks);
});