【问题标题】:How to encode/decode charset encoding in NodeJS?如何在 NodeJS 中编码/解码字符集编码?
【发布时间】:2013-09-10 14:23:07
【问题描述】:

我有这个代码:

request({ url: 'http://www.myurl.com/' }, function(error, response, html) {
  if (!error && response.statusCode == 200) {
    console.log($('title', html).text());
  }
});

但是我抓取的网站可以有不同的字符集(utf8、iso-8859-1 等)。如何获取它并将 html 编码/解码为正确的编码(utf8)?

感谢和抱歉我的英语;)

【问题讨论】:

  • 好吧,我知道我可以使用选项encoding 进行请求,但问题是我还不知道页面的字符集(我知道标题或元标记)

标签: encoding utf-8 character-encoding node.js


【解决方案1】:

网站可以在返回的 HTML 中返回 content-type 标头中的内容编码或 content-type 元标记,例如:

<meta http-equiv="Content-Type" content="text/html; charset=latin1"/>

您可以使用charset 模块自动为您检查这两项。不过,并非所有网站或服务器都会指定编码,因此您需要退回到从数据本身检测字符集。 jschardet 模块可以帮助您。

一旦您确定了字符集,您就可以使用 iconv 模块进行实际的转换。这是一个完整的例子:

request({url: 'http://www.myurl.com/', encoding: 'binary'}, function(error, response, html) {
    enc = charset(response.headers, html)
    enc = enc or jchardet.detect(html).encoding.toLowerCase()
    if enc != 'utf-8'
        iconv = new Iconv(enc, 'UTF-8//TRANSLIT//IGNORE')
        html = iconv.convert(new Buffer(html, 'binary')).toString('utf-8')
    console.log($('title', html).text());
});

【讨论】:

    【解决方案2】:

    首先,您可以发送一个 Accept-Charset 标头,这将阻止网站以其他字符集发送数据。

    收到响应后,您可以检查 字符集 条目的 Content-Type 标头并进行适当的处​​理。

    当内容编码未知时,另一个技巧(我过去使用过)是尝试使用所有可能的内容编码进行解码,并坚持使用不会引发异常的那个(尽管在 python 中使用)。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多