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’) // 拿到所有urltopicUrls.push(href) }) var ep = new eventproxy();// //異步調用結束后,執行某些操作 ep.after(’topic_html’, topicUrls.length, function (topics) { //接收res.texttopics = 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);}) })})
問題解答
回答1:這并不是亂碼啊,如果是亂碼,所有的都亂了,應該是你編碼的問題。
回答2:我直接用postman去請求了你那個地址,并沒有出現你這種情況,所以我判斷是你IDE或者文本編輯器的問題,將格式設為 utf-8 。
相關文章:
1. html5 - ElementUI table中el-table-column怎么設置百分比顯示。2. python - 使用readlines()方法讀取文件內容后,再用for循環遍歷文件與變量匹配時出現疑難?3. 對mysql某個字段監控的功能4. css3 - less或者scss 顏色計算的知識應該怎么學?或者在哪里學?5. 注冊賬戶文字不能左右分離6. javascript - table列過多,有什么插件可以提供列排序和選擇顯示列的功能7. css - 網頁div區塊 像蘋果一樣可左右滑動 手機與電腦8. javascript - 數組的過濾和渲染9. html - vue項目中用到了elementUI問題10. JavaScript事件
