我尝试运行此代码并得到“未定义”。有谁知道这段代码有什么问题吗?
var casper = require('casper').create();
casper.start('http://casperjs.org/', function() {
this.echo(document.querySelector('a'));
});
casper.run();
最佳答案
CasperJS 构建在 PhantomJS 之上,PhantomJS 有两个上下文。内页上下文casper.evaluate()
是沙箱中的,并且是唯一可以访问 DOM 的。
DOM 节点无法传递到外部上下文,因此您需要返回可以使用的元素的一些表示形式:
this.echo(this.evaluate(function(){
return document.querySelector('a').href;
}));
我建议你研究一下 CasperJS 函数,这些函数是从中抽象出来的,比如 getElementInfo()
和 getElementAttribute()
.
PhantomJS documentation说:
Note: The arguments and the return value to the
evaluate
function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.Closures, functions, DOM nodes, etc. will not work!
关于javascript - 无法获取 CasperJS 的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29780489/