2013-11-21 98 views
0

我想用node.io上的node.js解析一個HTML頁面,這個頁面在變量中作爲字符串。如何使用node.io從node.js解析HTML?

我面臨着將HTML字符串作爲參數傳遞給我的node.io作業的麻煩。

這是我的代碼摘錄在我的節點文件nodeiotest.js

var nodeIOJob = require('./nodeiojobfile.js'); 
var nodeio = require('node.io'); 

vat htmlString = 'HTML String Here'; 

nodeio.start(nodeIOJob.job, function(err, output) { 
     console.log(output); 
}, true); 

下一個是我的文件nodeiojobfile.js的摘錄:

var nodeio = require('node.io'); 

var methods = { 
    input: ['xxxxxxxxxxxxxxxx'], // htmlString is suppossed to come here 
    run: function (num) { 
     console.log(num); 
     this.emit('Hello World!'); 
    } 
} 

exports.job = new nodeio.Job(methods); 

我怎麼把我的htmlString作爲參數我在另一個文件中的工作?

此外,收到文件後,我需要將其解析爲HTML並執行一些基本的CSS選擇(例如getElementById()等),並且需要計算某些HTML元素的offsetHeight。該文檔說我可以使用get()getHTML()方法來解析URL的html,但是字符串中的HTML怎麼辦?我如何解析它們?

爲了測試我使用他下面的HTML:

<div> 
    <p id="p1"> 
     Testing document 
    </p> 
</div> 

我想選擇<p>然後找出它的高度。

任何人都可以幫助我嗎? Thnx提前!

+0

好,擊毀了我的大腦,我的鍵盤上的按鍵我已經決定了它不能做,至少不是個小時後,沒有使它成爲一個非常低效率的任務....請讓我知道是否有人發現這個輕量級解決方案... –

回答

0

我不熟悉的node.io,但我想你想是這樣的:

// nodeiotest.js 
... 
var htmlString = 'HTML String Here'; 
nodeio.start(nodeIOJob.job(htmlString), function(err, output) { 
    console.log(output); 
}, true); 

// nodeiojobfile.js 
var nodeio = require('node.io'); 

module.exports.job = function(htmlString) { 
    var methods = { 
    input: [ htmlString ], 
    run : function (num) { 
     console.log(num); 
     this.emit('Hello World!'); 
    } 
    }; 
    return new nodeio.Job(methods); 
}; 
+0

thnx羅伯特,但對我來說更大的問題是找到服務器端的元素的高度,我似乎無法做到這一點與node.io和jsdom也有一個關於它的錯誤.....你可以建議這樣的解決方案,也許服務器端無頭像瀏覽器像phantomjs或類似的東西...... –

+0

@ SurenderThakran是的喲我將不得不使用類似瀏覽器的解決方案(例如您提到的PhantomJS)。 – robertklep

+0

我很害怕這個。你能建議任何與'node.js'兼容的瀏覽器嗎? PhantomJS不是作爲一個節點模塊出現的,而必須作爲子進程使用,如果我在命令行中運行無頭瀏覽器,我不確定如何獲取元素的高度。 –