2012-04-04 25 views
0

NOOB這裏的HTTP請求拉一個特定的字符串。我有一個HTTP請求,用於從特定網頁中提取所有內容。但是,我需要的只是一個特定的字符串:"Most recent instantaneous value: "。實際上,我實際上需要存儲下面的值value:。這裏是我的代碼:從node.js中

var http = require("http"); 

var options = { 
host: 'waterdata.usgs.gov', 
port: 80, 
path: '/ga/nwis/uv?cb_72036=on&cb_00062=on&format=gif_default&period=1&site_no=02334400', 
method: 'POST' 
}; 

var req = http.request(options, function(res) { 
console.log('STATUS: ' + res.statusCode); 
console.log('HEADERS: ' + JSON.stringify(res.headers)); 
res.setEncoding('utf8'); 
res.on('data', function (chunk) { 
console.log('BODY: ' + chunk); 
}); 
}); 

req.on('error', function(e) { 
console.log('problem with request: ' + e.message); 
}); 

// write data to request body 
req.write('data\n'); 
req.write('data\n'); 
req.end(); 

我意識到,我並不需要所有的console.log報表,但我需要保持console.log('BODY: ' + chunk);所以所有的數據下載的?

回答

0

從來沒有做到這一點,我做這個quick'n'dirty例子的方式。有plentyofmodules爲DOM遍歷,HTML/XML解析,等等...他們是很多安全那麼簡單的正則表達式。但是,只要你得到的總體思路:

var http = require("http"); 

var options = { 
    host: 'waterdata.usgs.gov', 
    port: 80, 
    path: '/ga/nwis/uv?cb_72036=on&cb_00062=on&format=gif_default&period=1&site_no=02334400', 
}; 

function extract (body, cb) { 
    if(!body) 
     return; 

    var matches=body.match(/Most recent instantaneous value: ([^ ]+) /); 
    if(matches) 
     cb(matches[1]); 
} 

http.get(options, function(res) { 
    res.setEncoding('utf8'); 
    res.on('data', function (chunk) { 
     extract(chunk, function(v){ console.log(v); }); 
    }); 
}).on('error', function(e) { 
    console.log('problem with request: ' + e.message); 
}); 

不知怎的,我也發送POST而不是GET請求時,得到了一個不同的頁面。所以我改變了這一點......

關於你提到的第二個問題:不,你不需要保留任何的console.log()語句。只需使用回調,一切都很好! :-)

+0

謝謝。你爲什麼認爲這種做法不安全?此外,此解決方案還打印字符串的兩個實例。我只需要第一個例子。我需要修飾符還是什麼? – mnort9 2012-04-04 17:46:15

+0

找出它爲什麼要打印數據兩次。 – mnort9 2012-04-04 21:51:49

+1

如果您只需要第一個值,只需在回調前添加回車。在解析HTML的[傑夫的意見(http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html)這件事,當然這個答案的話題我建議你閱讀: http://stackoverflow.com/a/1732454/479133 – 2012-04-04 23:51:05