This question already has an answer here:
这个问题在这里已有答案:
- Pass a JavaScript function as parameter 13 answers
传递JavaScript函数作为参数13答案
I'm using jQuery selectors for casper.js scraping. I understand that it's necessary to place the jQuery calls inside casper.evaluate()
.
我正在使用jQuery选择器进行casper.js抓取。我知道有必要将jQuery调用放在casper.evaluate()中。
The problem is that in the last of these following three functions, a ReferenceError: Can't find variable: $
is raised. The first two work absolutely fine.
问题是,在以下三个函数的最后一个中,一个ReferenceError:找不到变量:$被引发。前两个工作绝对没问题。
// On main page, scrape links to sub-pages.
function getLinks() {
var links = $('li.ds-artifact-item a');
return Array.prototype.map.call(links, function(e) {
return e.getAttribute('href');
});
}
// On main page, scrape sub-pages' titles.
function getTitles() {
var titles = $('li.ds-artifact-item a');
return Array.prototype.map.call(titles, function(e) {
return e.innerHTML;
});
}
// On sub-page, scrape document description.
function getDescription(){
var descriptions = $('td.label-cell:contains(date)');
return Array.prototype.map.call(descriptions, function(e) {
return e.innerHTML;
});
}
Here's the rest of the script, with the unimportant details obscured. Note that anotherValidPage
is a valid URL which returns HTTP 200 (success).
这是脚本的其余部分,不重要的细节模糊不清。请注意,anotherValidPage是一个返回HTTP 200(成功)的有效URL。
var links = []; var titles = []; var descriptions = [];
casper.start(validPage, function() {
links = this.evaluate(getLinks);
titles = this.evaluate(getTitles);
});
casper.then(function() {
// echo results
this.echo(links.length + ' links found:');
this.echo(' - ' + links.join('\n - '));
this.echo(titles.length + ' titles found:');
this.echo(' - ' + titles.join('\n - '));
});
casper.thenOpen(anotherValidPage, function(){});
casper.then(function(){
// This call is the problematic one.
descriptions = this.evaluate(getDescription());
this.echo(descriptions.length + ' descriptions found:');
this.echo(' - ' + descriptions.join('\n - '));
});
casper.run();
1 个解决方案
#1
0
I found the solution: instead of calling this.evaluate(getDescription())
I had to call this.evaluate(getDescription)
, since I guess I was executing the function instead of passing it as an argument, whoops.
我找到了解决方案:而不是调用this.evaluate(getDescription())我不得不调用this.evaluate(getDescription),因为我想我正在执行函数而不是将其作为参数传递,哎呀。
#1
0
I found the solution: instead of calling this.evaluate(getDescription())
I had to call this.evaluate(getDescription)
, since I guess I was executing the function instead of passing it as an argument, whoops.
我找到了解决方案:而不是调用this.evaluate(getDescription())我不得不调用this.evaluate(getDescription),因为我想我正在执行函数而不是将其作为参数传递,哎呀。