2015-07-11 55 views
0

這是用於在網頁中抓取HTML DOM的PhantomJS腳本。用於等待所有DOM準備好如何將此PhantomJS腳本更改爲NodeJS進行網頁抓取

//scrap_phantom.js 
var server = require("webserver").create(); 
var page = require("webpage").create(); 
var port = require('system').env.PORT || 3000; 
var url = "http://www.example.com"; 

server.listen(port, function (request, response) { 
    function onPageReady() { 
     var htmlContent = page.evaluate(function() { 
      return document.documentElement.outerHTML; 
     }); 
     response.write(htmlContent); 
     response.close(); 
     phantom.exit(); 
    } 
    page.open(url, function (status) { 
     function checkReadyState() { 
      setTimeout(function() { 
       var readyState = page.evaluate(function() { 
        return document.readyState; 
       }); 
       if ("complete" === readyState) { 
        onPageReady(); 
       } else { 
        checkReadyState(); 
       } 
      }); 
     } 
     checkReadyState(); 
    }); 
}); 

我正在用「phantomjs scrap_phantom.js」在cmd中測試它。上面的代碼將工作。現在,我改變了代碼,腳本的NodeJS像這樣:

//scrap_node.js 
var http = require("http"); 
var phantom = require('phantom'); 
var url = "http://www.example.com"; 

http.createServer(function(request, response) { 
    function onPageReady() { 
     var htmlContent = page.evaluate(function() { 
      return document.documentElement.outerHTML; 
     }); 
     response.write(htmlContent); 
     response.close(); 
     phantom.exit(); 
    } 

phantom.create(function (ph) { 
    return ph.createPage(function (page) { 
     page.open(url, function (status) { 
      function checkReadyState() { 
       setTimeout(function() { 
        var readyState = page.evaluate(function() { 
         return document.readyState; 
        }); 
        if ("complete" === readyState) { 
         onPageReady(); 
        } else { 
         checkReadyState(); 
        } 
       }); 
      } 
      checkReadyState(); 
     }); 
    }); 
    }, { 
     dnodeOpts: {weak: false} 
    }); 
}).listen(3000); 

我與「節點scrap_node.js」測試它在cmd中。此代碼不適用於我。它正在加載很長時間,並且不會返回任何錯誤。爲什麼它不適合我?

+0

「這段代碼不適合我」不適合描述正在發生的事情。你看到錯誤嗎?什麼是輸出和你期望會發生什麼? –

+0

「http://www.example.com」即「http://pantip.com/topic/31403893」@ArtjomB。很長一段時間的負載...沒有任何錯誤返回。我沒看到它。瀏覽器在localhost:3000 show >>>無法加載網頁,因爲服務器沒有發送任何數據。 <<< –

回答

0

您的代碼有多個問題。

phantomjs-node是node.js和PhantomJS之間的橋樑。它使用稍微不同的語法,而且它的功能都不同步。這意味着,如果你寫這PhantomJS:

var result = page.evaluate(function(arg1, arg2){ 
    //...1 
    return stuff; 
}, "arg1", "arg2"); 
//...2 

然後在phantomjs節點(見Functionality Details)相當於是這樣的:

page.evaluate(function(arg1, arg2){ 
    //...1 
    return stuff; 
}, function(result){ 
    //...2 
}, "arg1", "arg2"); 

它本質上是異步的。

另一件事phantom沒有exit功能,但ph呢。

此外,setTimeout(function(){...})沒有做任何有用的事情。您需要傳遞一些超時值以使其有用。

+0

感謝您的幫助,我會檢查它 –