node.js - 使用 superagent 抓取 UTF-8网站乱码
本文介绍了node.js - 使用 superagent 抓取 UTF-8网站乱码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
我使用 superagent + cheerio 去抓取*东的商品 但是返回的中文乱码 响应头如下
是经过 gzip压缩的 但是按道理 superagent好像会默认解压
*东商品地址https://item.jd.com/5025518.html
我取了商品标题 结果如下
核心代码如下:
var url = 'https://list.jd.com/list.html?cat=670,671,672' //京东电脑
var totalData = [] // 存储总数据
superagent.get(url).end(function (err, res) {
if (err) {
return console.error(err)
}
var topicUrls = []; // 页面里面的所有url
var $ = cheerio.load(res.text) // 拿到页面
$('#plist .gl-item').each(function (i, e) {
$e = $(e)
var href = 'https:' + $e.find('.p-img >a').attr('href') // 拿到所有url
topicUrls.push(href)
})
var ep = new eventproxy();//
//异步调用结束后,执行某些操作
ep.after('topic_html', topicUrls.length, function (topics) { //接收res.text
topics = topics.map(function (topicHtml) {
var $ = cheerio.load(topicHtml, {decodeEntities: false});
return ({
title: $('.sku-name').text().trim()
});
});
totalData.push(topics)
console.log(totalData);
})
topicUrls.forEach(function (e) {
superagent.get(e).end(function (err, res) {
ep.emit('topic_html', res.text);
})
})
})
解决方案
你需要这个插件
superagent-charset
var request = require('superagent')
var superagent=require('superagent-charset')(request)
superagent
.get('http://')
.charset() //指定编码或者为空,为空为自动模式
.end(function(){
})
这篇关于node.js - 使用 superagent 抓取 UTF-8网站乱码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文