nodejs爬虫superagent爬取gb2312编码网页中文乱码

178 阅读1分钟

本文源自道招网的# nodejs爬虫superagent爬取gb2312编码网页中文乱码

今天爬取某个古老的网站的数据,发现中文乱码。

这个网站从外观上看也够古老的,是偏政企类网页,这种项目一般也都是外包出去的,技术更新速度也是可想而知,里面竟然还是写死的gb2312,还有三层table嵌套。

file

在网上搜了下,有的不少文章说的可能方法是过时,反正我实测没效果。

在npm上搜了下superagent,发现官方就提到了一个charset插件superagent-charsetsuperagent-charset官方github上就给出来示例代码。

const should = require('should')
const request = require('superagent')
require('superagent-charset')(request) // install charset

describe('Basic Test', function() {
  it('it works', function(done) {
    request.get('http://www.sohu.com/')
      .charset('gbk')
      .end((err, res) => {
        res.text.should.match(/搜狐/)
        done(err)
      })
  })
})

果然,搞定了。

const superagent= require('superagent');
require('superagent-charset')(superagent)
const cheerio = require('cheerio');

function getResponse(url, charset = 'utf8') {
  return new Promise((resolve, reject) => {
    superagent.get(url)
      .buffer(true).charset(charset)
      .end((err, res) => {
      if (err) {
        reject(err);
      } else {
        resolve(res);
      }
    });
  });
}