从Phantomjs + node.js中调用外部函数

时间:2017-04-13 07:15:29

标签: node.js phantomjs

我说实话。我在这里过得很开心。

我需要从我的雇主的动态网站上抓取数据。在页面上显示数据之前,需要进行一些点击和等待。简单的PHP抓取不会做。所以我发现了这个NodeJS + PhantomJS组合。设置相当痛苦,但我确实设法加载一个站点,运行一些代码并获得结果。

我写了一段jQuery,它使用超时循环来等待加载一些数据。最终我得到一个我要写入文件(JSON)的js对象。

我面临的问题。 我在PhantomJS .evaluate范围内构建了js对象,该范围在无头浏览器中运行,因此不能直接在我的Node.JS服务器范围内运行。如何将我在里面构建的变量发送回我的服务器,以便将其写入我的文件?

一些示例代码(我知道它很丑陋,但出于说明目的)。我使用node-phantom-simple作为Phantom和Node之间的桥梁



var phantom = require('node-phantom-simple'),
  fs = require('fs'),
  webPage = 'https://www.imagemedia.com/printing/business-card-printing/'

phantom.create(function(err, ph) {
  return ph.createPage(function(err, page) {
    return page.open(webPage, function(err, status) {
      page.onConsoleMessage = function(msg) {
        console.log(msg);
      };
      console.log("opened site? ", status);
      page.evaluate(function() {
        setTimeout(function() {
          $('.price-select-cnt').eq(0).find('select').val('1266').change()
          timeOutLoop()

          function timeOutLoop() {
            console.log('looping')
            setTimeout(function() {
              if ($('#ajax_price_tool div').length != 6) {
                timeOutLoop()
              } else {
                $('.price-select-cnt').eq(1).find('select').val('25')
                $('.price-select-cnt').eq(2).find('select').val('Premium Card Stock')
                $('.price-select-cnt').eq(3).find('select').val('Standard').change()
                timeOutLoop2()
              }
            }, 100)
          }

          function timeOutLoop2() {
            console.log('looping2')
            setTimeout(function() {
              if ($('.pricing-cost-cnt').text() == '$0' || $('.pricing-cost-cnt').text() == '') {
                timeOutLoop2()
              } else {
                var price = $('.pricing-cost-cnt').text()
                console.log(price)
              }
            }, 100)
          }
        }, 4000)
      });
    });
  });
});

function writeJSON(plsWrite) {
  var key = 'file'
  fs.writeFile('./results/' + key + '.json', plsWrite, 'utf8', function() {
    console.log('The JSON file is saved as');
    console.log('results/' + key + '.json');
  });
}




那么我是否应该从网站上编写此代码的价格,将其从评估范围中删除并将其写入文件?

0 个答案:

没有答案