Express app.get() equivalent in CasperJS

Express app.get() equivalent in CasperJS

本文关键字:equivalent in CasperJS app get Express      更新时间:2023-09-26

我构建了一个简单的网络抓取器,它可以抓取网站并在访问此URL时输出所需的数据 - localhost:3434/page .我使用快速app.get()方法实现了此功能。

我有以下问题,

1(我想知道是否有办法在CasperJS中实现此功能。

2(有没有办法在我访问URL - localhost:8081/scrape后使此代码开始抓取。我认为我没有正确创建端点,因为它在我访问 URL
之前就开始抓取

3(当我访问URL时,它给我一个错误,说URL不可用。

我认为如果我能在 CasperJS 中正确将终点设置为localhost:3434/page,所有这些问题都将得到解决。我不需要结果出现在页面上。我只需要它在访问该 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服务器模块,它"旨在方便PhantomJS脚本与外界之间的通信,建议用作一般生产服务器">

你不应该在PhantomJS中构建你的Web服务器。查看这些节点幻像桥,它们可以让您从常规的 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允许从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的那些,还有其他的:

  • https://github.com/segmentio/nightmare
  • https://github.com/assaf/zombie

ZombieJS使用本机NodeJS库,这使得它在NodeJS应用程序中使用最快,最自然。尽管它更多地用于测试目的,并且可能无法在其他抓取工具可能的所有站点上运行。