Node作網頁爬蟲時遇到的Html entites對象形成亂碼

Node作網頁爬蟲時遇到的Html entites對象形成亂碼css

就是文字內容是這種貨:html

 ��һҳ node

嘗試用iconv-lite模塊的decode去轉碼,可是失敗了。網頁爬蟲

這種叫HTML Entities,能夠藉助一些模塊來轉換,好比,html-entities Github。ui

HTML Entities是什麼請參照以下網址:編碼

http://www.w3school.com.cn/html/html_entities.aspspa

html-entities的使用方法以下code

var Entities = require('html-entities').XmlEntities;
entities = new Entities();
var str = '��һҳ';
console.log(entities.decode(str)); 

在爬蟲的請求上也要調整:htm

1 var headers = {  
2   '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'
3 }

加上簡單的假裝對象

使用Node爬的話,應該會用cheerio,在接受request返回的網頁內容時,仍是通過iconv的轉換,再用cheerio

1 var html = iconv.decode(body, 'gbk')
2 var $ = cheerio.load(html, {decodeEntities: false})

若是你不知道抓取的網頁的編碼的話,請使用:

 res.headers['content-type']  

根據返回的編碼格式進行處理便可

關於網頁內容轉碼和亂碼的深層分析能夠閱讀以下博文:

http://www.dewen.io/q/13755

http://www.99css.com/nodejs-request-chinese-encoding/

這個帥哥的分析也頗有趣

http://blog.vichamp.com/program/2015/07/04/Common-Messy-Code/

相關文章
相關標籤/搜索