首页 > nodejs爬虫爬取网站的时候中文乱码问题

nodejs爬虫爬取网站的时候中文乱码问题

用nodejs在未知网站编码的时候 爬取网站内容 如何才能不中文乱码。

在已知网站的编码的情况下,我已经知道如何处理了。未知网站编码的情况下海不知道了,求大大赐教


可以先从网页的meta里判断一下charset,然后再用iconv转

javascriptrequire("request").get({ url : url ,encoding : null} ,function(err, response, body){
  var charset="utf-8";
  var arr=body.toString().match(/<meta([^>]*?)>/g);
  if(arr){
    arr.forEach(function(val){
      var match=val.match(/charset\s*=\s*(.+)\"/);
      if(match && match[1]){
        if(match[1].substr(0,1)=='"')match[1]=match[1].substr(1);
        charset=match[1].trim();
        return false;
      }
    })
  }

  var data = require('iconv-lite').decode(body, charset);
  // console.log(data);
})
【热门文章】
【热门文章】