【问题标题】:HTML parser: convert html ISO-8859-1 encoded text to UTF-8HTML 解析器:将 html ISO-8859-1 编码文本转换为 UTF-8
【发布时间】:2020-06-13 10:29:20
【问题描述】:

我正在尝试使用 Beautiful Soup 在 python 3.7 中构建一个 html 邮件解析器。

邮件头中的Content-Type是:text/html; charset="iso-8859-1"

这是一些html代码:

<div dir='3D"ltr"' id='3D"divRplyFwdMsg"'>
         <font color='3D"#000000"' face='=3D"Calibri,' sans-serif"="" style='3D"font-size:11pt"'>
          <b>
           Enviado:
          </b>
          jueves, 9 de mayo de 2019 11:16
          <br/>
          <b>
           Para:
          </b>
          DealReg
          <br/>
          <b>
           Asunto:
          </b>
          Integrated Quoting - Deal Registration ID 001009814954 pa=
ra Cliente client_name Revisi=F3n completa
         </font>
         <div>
         </div>

我需要使用 UTF-8 正确编码文本。

“综合报价 - 交易注册 ID 001009814954 pa= ra Cliente client_name Revisi=F3n completa”我期望“综合报价 - 交易注册 ID 001009814954 para Cliente client_name Revisión completa”

我找到了一些解决方案,但没有一个适合我:

[1].

with codecs.open(html_path,"r", encoding = "utf-8") as html_file:
           text = html_file.read()

[2].

with io.open(html_path,"r", encoding = "utf-8") as html_file:
           text = html_file.read()

[3].

a = "Revisi=F3n"
b = a.encode("iso-8859-1").decode("utf-8")

>>>print(b)
"Revisi=F3n"

在 [3] 中,我还尝试使用 ascii、latin-1、cp1252 进行编码,结果是一样的。

谢谢!

【问题讨论】:

    标签: python html encoding utf-8 html-parsing


    【解决方案1】:

    看起来非 ascii 字符已使用 quoted printable 编码进行编码(也许此 html 来自电子邮件?)。 quopri 模块可用于将它们编码为bytes,然后可以将其解码为str

    >>> import quopri
    >>> s = 'Revisi=F3n'      
    >>> quopri.decodestring(s)
    b'Revisi\xf3n'   # bytes
    >>> quopri.decodestring(s).decode('ISO-8859-1')
    'Revisión'
    

    quopri.decode 函数将解码整个文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 2013-07-20
      相关资源
      最近更新 更多