【发布时间】:2018-03-29 08:31:38
【问题描述】:
我收到了一段表示 HTML 的文本,例如:
<html>\r\n<head>\r\n<meta http-equiv=3D\"Content-Type\" content=3D\"text/html; charset=3DWindows-1=\r\n252\">\r\n<style type=3D\"text/css\" style=3D\"display:none;\"><!-- P {margin-top:0;margi=\r\nn-bottom:0;} --></style>\r\n</head>\r\n<body dir=3D\"ltr\">This should be a pound sign: =A3 and this should be a long dash: =96 \r\n</body>\r\n</html>\r\n
从 HTML <meta> 标记中我可以看到这段 HTML 应该被编码为 Windows-1252。
我正在使用 node.js 来解析这段带有cheerio 的文本。然而,使用https://github.com/mathiasbynens/windows-1252 对其进行解码并没有帮助:windows1252.decode(myString); 会返回相同的输入字符串。
我认为的原因是该输入字符串已经在标准 node.js 字符集中进行了编码,但它实际上 表示 一段windows-1252 编码的 HTML(如果这有意义的话?)。
检查= 前面的那些奇怪的十六进制数字,我可以看到有效的windows-1252 代码,例如:
- 这个
=\r\n和这个\r\n应该以某种方式代表Windows 世界中的回车, -
=3D: HEX3D是 DEC61这是一个等号:=, -
=96:HEX96是 DEC150,这是一个“短划线”符号:–(某种“长减号”), -
=A3: HEXA3是 DEC163这是一个井号:£
我无法控制那段 HTML 的生成,但我应该解析并清理它并返回 £(而不是 =A3)等。
现在,我知道我可以将转换保存在内存映射中,但我想知道是否已经存在涵盖整个 windows-1252 字符集的编程解决方案?
参照。这是整个转换表:https://www.w3schools.com/charsets/ref_html_ansi.asp
编辑:
输入的 HTML 来自 IMAP 会话,因此上游似乎存在我无法控制的 7 位/8 位“引用的可打印编码”(参见 https://en.wikipedia.org/wiki/Quoted-printable)。
与此同时,我意识到了这种额外的编码,我尝试了这个quoted-printable(参见https://github.com/mathiasbynens/quoted-printable)库,但没有成功。
以下是 MCV(根据要求):
var cheerio = require('cheerio');
var windows1252 = require('windows-1252');
var quotedPrintable = require('quoted-printable');
const inputString = '<html>\r\n<head>\r\n<meta http-equiv=3D\"Content-Type\" content=3D\"text/html; charset=3DWindows-1=\r\n252\">\r\n<style type=3D\"text/css\" style=3D\"display:none;\"><!-- P {margin-top:0;margi=\r\nn-bottom:0;} --></style>\r\n</head>\r\n<body dir=3D\"ltr\">This should be a pound sign: =A3 and this should be a long dash: =96 \r\n</body>\r\n</html>\r\n'
const $ = cheerio.load(inputString, {decodeEntities: true});
const bodyContent = $('html body').text().trim();
const decodedBodyContent = windows1252.decode(bodyContent);
console.log(`The input string: "${bodyContent}"`);
console.log(`The output string: "${decodedBodyContent}"`);
if (bodyContent === decodedBodyContent) {
console.log('The windows1252 output seems the same of as the input');
}
const decodedQp = quotedPrintable.decode(bodyContent)
console.log(`The decoded QP string: "${decodedQp}"`);
前面的脚本产生以下输出:
The input string: "This should be a pound sign: =A3 and this should be a long dash: =96"
The output string: "This should be a pound sign: =A3 and this should be a long dash: =96"
The windows1252 output seems the same of as the input
The decoded QP string: "This should be a pound sign: £ and this should be a long dash: "
在我的命令行上,我看不到长破折号,我不确定如何正确解码所有这些=<something> 编码字符?
【问题讨论】:
-
看来你在这里很不走运。
-
我认为您需要提供更完整的minimal reproducible example。首先,文本是如何从任何地方进入您的程序的?
标签: html node.js character-encoding windows-1252 quoted-printable