CNode

完整探测一个未知页面的文本编码

精华
分享
Ffengmk2发布于12 年前最后回复12 年前6 回复8703 浏览0 收藏

写过爬虫的同学,都会遇到 “body怎么是乱码” 的类似问题。结合 charsetjschardet 两个模块,可以完整地探测出一个页面的具体文本编码。

废话不多说了,上代码 encoding.js:

var urllib = require('urllib');
var charset = require('charset');
var jschardet = require('jschardet');

var url = process.argv[2] || 'http://www.taobao.com';

urllib.request(url, function (err, body, res) {
  if (err) throw err;
  var encoding = charset(res, body);
  console.log('detect %j from charset', encoding);
  if (!encoding) {
    encoding = jschardet.detect(body).encoding;
    console.log('detect %j from jschardet', encoding);
  }
});

运行结果:

$ node encoding.js http://www.tmall.com
detect "gbk" from charset

$ node encoding.js http://tmall.com
detect null from charset
detect "ascii" from jschardet
查看回复

回复 (6)

F
fengmk2#1·12 年前

找不到一个headers 和 meta 都没有编码的页面,大家可以找找看。

Y
yaochun#2·12 年前

哈哈,错别字哦 - boody,处女座的命啊

B
borisyu#3·12 年前

不错!

C
CocaCola183#4·12 年前

L
Lenchs#5·12 年前

T
think2011#6·12 年前

啊,是什么原理? 不知道编码也能够检测。

参与回复
登录后即可参与回复。登录