我刚刚为 pjscrape 编写了第一个脚本,但我发现它运行速度非常慢。我对 pjscrape 和 phantomjs 都很陌生,所以我不知道哪一个是罪魁祸首。
我从本地主机加载文件,所以瓶颈肯定不在传输中。
我的config.js脚本如下所示:
pjs.addSuite({
url: 'http://localhost/file.html'.
scraper: function() {
var people = $('table.person');
var results = [];
$.each(people, function() {
var $this = $(this);
results.push({
firstName: $this.find('.firstName').text(),
lastName: $this.find('.lastName').text(),
age: $this.find('.age').text()
});
}
return results;
}
}
然后我只需使用命令行指令 here 执行 PhantomJS 。
~> phantomjs pjscrape.js config.js
我在 Chrome 中运行相同的代码(只是 scraper function() ),它是即时的。在 phantomjs/pjscrape 中,需要 30 秒。
知道是什么原因导致速度缓慢吗?
是否有更好的方法来进行 DOM 屏幕抓取?也许是一个nodejs解决方案?
最佳答案
如果可以选择 Node.JS,我可以向您介绍 cheerio ?它是一个很棒的库,用于使用格式有问题的 HTML 文档。它为您提供了一个类似 jQuery 的 API,用于处理您正在抓取的页面的类似 DOM 的表示形式。与 request 配对,它为抓取 HTML 提供了一个非常简单的环境。
您的示例最终看起来像这样(错误处理留给读者作为练习):
var cheerio = require("cheerio"),
request = require("request");
request("http://localhost/file.html", function(err, res, data) {
var $ = cheerio.load(data);
var people = $('table.person');
var results = [];
$.each(people, function() {
var $this = $(this);
results.push({
firstName: $this.find('.firstName').text(),
lastName: $this.find('.lastName').text(),
age: $this.find('.age').text()
});
}
do_something_with(results);
});
关于javascript - 是pjscrape慢还是PhantomJS慢?替代刮刀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17366217/