gpt4 book ai didi

javascript - Casper JS 运行方法提前触发

转载 作者:行者123 更新时间:2023-11-30 17:31:17 24 4
gpt4 key购买 nike

向函数添加 this.echo 命令会导致在设置链接之前调用 casper.run 方法

var casper = require('casper').create();

function getLinks() {
this.echo("Getting links"); // <--------- This line cause everything to fail
var links = document.querySelectorAll('table');
return Array.prototype.map.call(links, function(e) {
return e.getAttribute('id');
});
}

var links = [];

casper.start('example.html', function() {
links = this.evaluate(getLinks);
});

casper.run(function() {
this.echo(links.length + ' links found:');
this.echo(' - ' + links.join('\n - ')).exit();
});

最佳答案

从未使用过 casper.js,但来自 documentation :

As a reminder, think of the evaluate() method as a gate between the CasperJS environment and the one of the page you have opened; everytime you pass a closure to evaluate(), you’re entering the page and execute code as if you were using the browser console.

因此,this 可能不是指 casper,而是指文档的全局对象。 this.echo 不存在并抛出错误,函数的其余部分不会执行,也不会收集任何链接。所以,并不是传递给 run 的回调函数提前执行了,只是收集链接的代码从未运行过。

尝试使用 casper.echo("Getting links");,或者简单地删除调用并将其移动到 start 中:

casper.start('example.html', function() {
this.echo("Getting links");
links = this.evaluate(getLinks);
});

关于javascript - Casper JS 运行方法提前触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23033856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com