鍍金池/ 問答/HTML/ 在NodeJS里使用http.get方法為什么無法獲取到這一特定網(wǎng)頁的內(nèi)容?

在NodeJS里使用http.get方法為什么無法獲取到這一特定網(wǎng)頁的內(nèi)容?

在NodeJS里使用http.get方法,平時(shí)獲取各種網(wǎng)頁返回的內(nèi)容都很正常,最近碰到“上觀新聞”的站點(diǎn)很奇怪,例如:

欄目列表頁 http://web.shobserver.com/new...
詳情頁 http://web.shobserver.com/new...

通過http.get方法返回的response是空白,也沒有錯(cuò)誤提示,不知道該站點(diǎn)有什么特殊之處?

代碼如下:

http.get(url,function(res){
    var html = '';
    res.setEncoding('utf-8');
    res.on('data',function(chunk){
        html += chunk;
    });
    res.on('end',function(){
        //解析html
    });
});
回答
編輯回答
汐顏

設(shè)置User-Agent即可

var http=require("http");
var req=http.get({
    hostname: 'web.shobserver.com',
    port: 80,
    path: '/news/sublist?section=33',
    method: 'GET',
    headers:{
        'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
    }
},function(res){
    var html = '';
    res.setEncoding('utf-8');
    

    res.on('data',function(chunk){
        html += chunk;
    });
    res.on('end',function(){
        //解析html
        console.log(html);
    });
});
2018年2月5日 02:51
編輯回答
雨萌萌

這種問題很常見,在請(qǐng)求的 headers 里加上 User-Agent 模擬正常的瀏覽器就行了。
原生http比較難用,我就用 request 示例:

var request = require("request");

var options = { 
    method: 'GET',
    url: 'http://web.shobserver.com/news/sublist',
    qs: { section: '33' },
    headers: { 
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36'
    } 
};

request(options, function (error, response, body) {
  if (error) console.log(error);

  console.log(body);
});
2017年11月30日 09:47