我构建了一个简单的网络抓取工具,当我访问此 URL - localhost:3434/page
时,它会抓取网站并输出我需要的数据。 。我使用 Express app.get()
实现了此功能方法。
我有以下问题,
1) 我想知道是否有办法在 CasperJS 中实现此功能。
2) 有没有办法让这段代码在我访问 URL - localhost:8081/scrape
后开始抓取。我认为我没有正确创建端点,因为它在我访问 URL 之前就开始抓取
3) 当我访问该 URL 时,它给出一条错误消息,指出该 URL 不可用。
我想如果我能将终点正确设置为localhost:3434/page
,所有这些问题都将得到解决。在 CasperJS 中。我不需要结果出现在页面上。我只需要它在访问该 URL 时开始抓取。
下面是我开发的用于抓取网站并在 Casper 中创建服务器的代码。
var server = require('webserver').create();
var service = server.listen(3434, function(request, response) {
var casper = require('casper').create({
logLevel:"verbose",
debug:true
});
var links;
var name;
var paragraph;
var firstName;
var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
casper.start('http://www.home.com/professionals/c/oho,-TN');
casper.then(function getLinks(){
links = this.evaluate(function(){
var links = document.getElementsByClassName('pro-title');
links = Array.prototype.map.call(links,function(link){
return link.getAttribute('href');
});
return links;
});
});
casper.then(function(){
this.each(links,function(self,link){
if (link.match(regex)) {
self.thenOpen(link,function(a){
var firstName = this.fetchText('div.info-list-text');
this.echo(firstName);
});
}
});
});
casper.run(function() {
response.statusCode = 200;
response.write(firstName);
response.close();
});
});
最佳答案
您在 CasperJS 脚本中使用的 webserver
是 PhantomJS 的 Web Server Module “旨在方便 PhantomJS 脚本与外界之间的通信,不建议用作通用生产服务器”
您不应该在 PhantomJS 中构建您的 Web 服务器。查看这些 Node 幻影桥,它们可以让您从常规 NodeJS Web 服务器使用 Phantom:
- https://github.com/SpookyJS/SpookyJS
- https://github.com/peerigon/phridge
- https://github.com/baudehlo/node-phantom-simple
- https://github.com/johntitus/node-horseman
- https://github.com/nodeca/navit
SpookyJS 是专门针对 CasperJS 的驱动程序,而其他驱动程序仅适用于 PhantomJS。
虽然CasperJS allows being loaded from within PhantomJS所以你至少可以在 Phridge 中使用它(不确定其他的),因为它有一个 .run
函数,可以直接在 PhantomJS 环境中运行任何函数:
casperPath = path.join(require.resolve('casperjs/bin/bootstrap'), '/../..');
phantom.run(casperPath, function(casperPath) {
phantom.casperPath = casperPath;
phantom.injectJs(casperPath + '/bin/bootstrap.js');
casper = require('casper').create();
...
<小时/>
除了使用 PhantomJS 的之外,还有其他的:
ZombieJS 使用原生 NodeJS 库,这使得它在 NodeJS 应用程序中使用起来最快、最自然。尽管它更多地用于测试目的,并且可能无法像其他抓取工具一样在所有网站上工作。
关于javascript - CasperJS 中的 Express app.get() 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35229333/