簡體   English   中英

使用PhantomJS和node.js保存並呈現網頁

[英]Save and render a webpage with PhantomJS and node.js

我正在尋找一個請求網頁,等待JavaScript呈現(JavaScript修改DOM),然后抓取頁面的HTML的示例。

這應該是一個簡單的例子,有一個明顯的PhantomJS用例。 我找不到一個體面的例子,文檔似乎都是關於命令行使用的。

根據你的評論,我猜你有兩個選擇

  1. 嘗試找到一個phantomjs節點模塊 - https://github.com/amir20/phantomjs-node
  2. 將phantomjs作為節點內的子進程運行 - http://nodejs.org/api/child_process.html

編輯:

似乎phantomjs建議將子進程作為與節點交互的一種方式,請參閱faq - http://code.google.com/p/phantomjs/wiki/FAQ

編輯:

用於獲取頁面HTML標記的示例Phantomjs腳本:

var page = require('webpage').create();  
page.open('http://www.google.com', function (status) {
    if (status !== 'success') {
        console.log('Unable to access network');
    } else {
        var p = page.evaluate(function () {
            return document.getElementsByTagName('html')[0].innerHTML
        });
        console.log(p);
    }
    phantom.exit();
});

使用phantomjs-node v2,在處理HTML之后很容易打印HTML。

var phantom = require('phantom');

phantom.create().then(function(ph) {
  ph.createPage().then(function(page) {
    page.open('https://stackoverflow.com/').then(function(status) {
      console.log(status);
      page.property('content').then(function(content) {
        console.log(content);
        page.close();
        ph.exit();
      });
    });
  });
});

這將顯示使用瀏覽器呈現的輸出。

編輯2019:

您可以使用async/await

const phantom = require('phantom');

(async function() {
  const instance = await phantom.create();
  const page = await instance.createPage();
  await page.on('onResourceRequested', function(requestData) {
    console.info('Requesting', requestData.url);
  });

  const status = await page.open('https://stackoverflow.com/');
  const content = await page.property('content');
  console.log(content);

  await instance.exit();
})();

或者,如果您只是想測試,可以使用npx

npx phantom@latest https://stackoverflow.com/

我過去曾使用過兩種不同的方法,包括查詢Declan提到的DOM的page.evaluate()方法。 我從網頁傳遞信息的另一種方法是從那里吐出到console.log(),並在phantomjs腳本中使用:

page.onConsoleMessage = function (msg, line, source) {
  console.log('console [' +source +':' +line +']> ' +msg);
}

我也可能在onConsoleMessage中捕獲變量msg並搜索一些封裝數據。 取決於您想如何使用輸出。

然后在Nodejs腳本中,您必須掃描Phantomjs腳本的輸出:

var yourfunc = function(...params...) {
  var phantom = spawn('phantomjs', [...args]);
  phantom.stdout.setEncoding('utf8');
  phantom.stdout.on('data', function(data) {
    //parse or echo data
    var str_phantom_output = data.toString();
    // The above will get triggered one or more times, so you'll need to
    // add code to parse for whatever info you're expecting from the browser
  });
  phantom.stderr.on('data', function(data) {
    // do something with error data
  });
  phantom.on('exit', function(code) {
    if (code !== 0) {
      // console.log('phantomjs exited with code ' +code);
    } else {
      // clean exit: do something else such as a passed-in callback
    }
  });
}

希望有所幫助。

為什么不用這個呢?

var page = require('webpage').create();
page.open("http://example.com", function (status)
{
    if (status !== 'success') 
    {
        console.log('FAIL to load the address');            
    } 
    else 
    {
        console.log('Success in fetching the page');
        console.log(page.content);
    }
    phantom.exit();
});

如果有人在這個問題上遇到困難,可以延遲更新:

我的一位同事開發的GitHub項目正是為了幫助你做到這一點: https//github.com/vmeurisse/phantomCrawl

它仍然有點年輕,它肯定缺少一些文檔,但提供的示例應該有助於進行基本爬行。

這是一個舊版本,我使用運行node,express和phantomjs將頁面保存為.png。 您可以相當快地調整它來獲取HTML。

https://github.com/wehrhaus/sitescrape.git

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM