Node.js 抓取非 utf-8 的中文网页时会出现乱码问题,比如网易的首页编码是 gb2312,抓取时会出现乱码
var request = require('request') var url = 'http://www.163.com'request(url, function (err, res, body) { console.log(body) })
安装
npm install iconv-lite
var originRequest = require('request') var iconv = require('iconv-lite') var headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36' }function request (url, callback) { var options = { url: url, encoding: null, headers: headers } originRequest(options, callback) }
request(url, function (err, res, body) { var html = iconv.decode(body, 'gb2312') console.log(html) })
乱码问题解决
使用 cheerio 解析 HTML
cheerio 可以简单粗暴的理解为服务器端 jQuery 选择器,有了它,比正则要更加直观许多
安装
npm install cheerio request(url, function (err, res, body) { var html = iconv.decode(body, 'gb2312') var $ = cheerio.load(html) console.log($('h1').text()) console.log($('h1').html()) })
网易 网易
解决 cheerio .html() 「乱码」问题
查阅文档可知,可以关闭这个转换实体编码的功能
var $ = cheerio.load(html)
var $ = cheerio.load(html, {decodeEntities: false})
var originRequest = require('request') var cheerio = require('cheerio') var iconv = require('iconv-lite') var headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36' }function request (url, callback) { var options = { url: url, encoding: null, headers: headers } originRequest(options, callback) }
var url = 'http://www.163.com'
request(url, function (err, res, body) { var html = iconv.decode(body, 'gb2312') var $ = cheerio.load(html, {decodeEntities: false}) console.log($('h1').text()) console.log($('h1').html()) })