node.js - 使用 superagent 抓取 UTF-8網站亂碼
天蓬老师
天蓬老师 2017-07-06 10:35:50
0
2
1331

我使用 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);
        })
    })


})
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回覆(2)
phpcn_u1582

這並不是亂碼啊,如果是亂碼,所有的都亂了,應該是你編碼的問題。

代言

我直接用postman去請求了你那個位址,並沒有出現你這種情況,所以我判斷是你IDE或文字編輯器的問題,將格式設為 utf-8 。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!