![](/img/trans.png)
[英]How to use phantomjs in node-js environment for dynamic-page web scraping?
[英]How to use PhantomJS along with node.js for scraping?
我已經通過npm install node-phantom
但是當我運行此代碼時,它給出了Cannot find module 'webpage'
錯誤
var webpage = require('webpage').create(),
url = "https://www.example.com/cba/abc",
hrefs = new Array();
webpage.open(url,function(status){
if(status=="success"){
var results = page.evaluate(function(){
$("#endpoints").each(function() {
hrefs.push($(this).attr("href"));
});
return hrefs;
});
console.log(JSON.stringify(results));
phantom.exit();
}
});
您不需要在node-phantom中使用網頁模塊。 您將使用其API來獲取網頁模塊的表示形式。 必須這樣做,因為PhantomJS與node.js具有不同的執行運行時。 他們通常不能使用相同的模塊。 這就是為什么在這兩個執行環境(例如node-phantom和phantom)之間建立橋梁的原因。 他們本質上復制了在node.js中使用的PhantomJS API。
根據文檔,您不需要該網頁,而是獲得一個頁面:
var phantom = require('node-phantom');
phantom.create(function(err,ph) {
return ph.createPage(function(err,page) {
// do something with page: basically your script
});
});
您將無法僅復制和粘貼現有的PhantomJS代碼。 兩者之間存在差異,因此您必須學習API(基本上是github上的README)。
完整的代碼翻譯:
var phantom = require('node-phantom');
phantom.create(function(err,ph) {
return ph.createPage(function(err,page) {
page.open(url,function(status){
if(status=="success"){
page.evaluate(function(){
hrefs = [];
$("#endpoints").each(function() {
hrefs.push($(this).attr("href"));
});
return hrefs;
}, function(err, results){
console.log(JSON.stringify(results));
ph.exit();
});
}
});
});
});
page.evaluate
仍然處於沙盒狀態,因此您不能像hrefs
這樣使用外部變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.