【问题标题】:Convert XML/HTML Entities into Unicode String in Python [duplicate]在 Python 中将 XML/HTML 实体转换为 Unicode 字符串 [重复]
【发布时间】:2010-09-08 15:11:59
【问题描述】:

我正在做一些网页抓取,并且网站经常使用 HTML 实体来表示非 ascii 字符。 Python 是否有一个实用程序可以接收带有 HTML 实体的字符串并返回 unicode 类型?

例如:

我回来了:

ǎ

代表带有声调的“ǎ”。在二进制中,这表示为 16 位 01ce。我想将html实体转换成值u'\u01ce'

【问题讨论】:

标签: python html entities


【解决方案1】:

你可以在这里找到答案——Getting international characters from a web page?

编辑:似乎BeautifulSoup 不会转换以十六进制形式编写的实体。可以修复:

import copy, re
from BeautifulSoup import BeautifulSoup

hexentityMassage = copy.copy(BeautifulSoup.MARKUP_MASSAGE)
# replace hexadecimal character reference by decimal one
hexentityMassage += [(re.compile('&#x([^;]+);'), 
                     lambda m: '&#%d;' % int(m.group(1), 16))]

def convert(html):
    return BeautifulSoup(html,
        convertEntities=BeautifulSoup.HTML_ENTITIES,
        markupMassage=hexentityMassage).contents[0].string

html = '<html>&#x01ce;&#462;</html>'
print repr(convert(html))
# u'\u01ce\u01ce'

编辑

@dF 提到的unescape() 函数使用htmlentitydefs 标准模块和unichr() 在这种情况下可能更合适。

【讨论】:

  • 此解决方案不适用于示例: print BeautifulSoup('ǎ', convertEntities=BeautifulSoup.HTML_ENTITIES) 这将返回相同的 HTML 实体
  • 注意:这仅适用于 BeautifulSoup 3,自 2012 年以来已弃用并被视为遗留。BeautifulSoup 4 自动处理此类 HTML 实体。
  • @MartijnPieters:正确。 html.unescape() 是现代 Python 的更好选择。
  • 当然。如果您只想解码 HTML 实体,则根本不需要使用 BeatifulSoup。
  • @MartijnPieters:在旧的 Python 版本上,除非 HTMLParser.HTMLParser().unescape() hack 对您有用,否则使用 BeautifulSoup 可能比手动定义 unescape() 更好(供应纯 Python 库与副本-粘贴函数)。
【解决方案2】:

使用内置的unichr -- BeautifulSoup 不是必需的:

>>> entity = '&#x01ce'
>>> unichr(int(entity[3:],16))
u'\u01ce'

【讨论】:

  • 但这要求您自动且明确地知道编码的 Unicode 字符在字符串中的哪个位置 - 您无法知道。当你弄错时,你需要try...catch 产生的异常。
  • unichar 在 python3 中被删除。对那个版本有什么建议吗?
【解决方案3】:

Python 有 htmlentitydefs 模块,但这不包括取消转义 HTML 实体的函数。

Python 开发者 Fredrik Lundh(elementtree 的作者等)拥有这样一个函数 on his website,它适用于十进制、十六进制和命名实体:

import re, htmlentitydefs

##
# Removes HTML or XML character references and entities from a text string.
#
# @param text The HTML (or XML) source text.
# @return The plain text, as a Unicode string, if necessary.

def unescape(text):
    def fixup(m):
        text = m.group(0)
        if text[:2] == "&#":
            # character reference
            try:
                if text[:3] == "&#x":
                    return unichr(int(text[3:-1], 16))
                else:
                    return unichr(int(text[2:-1]))
            except ValueError:
                pass
        else:
            # named entity
            try:
                text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
            except KeyError:
                pass
        return text # leave as is
    return re.sub("&#?\w+;", fixup, text)

【讨论】:

  • 当然。为什么不在标准库中?
  • 查看它的代码,它似乎不适用于&amp;amp; 等,是吗?
  • 刚刚成功测试&
【解决方案4】:

这个函数可以帮助您正确处理并将实体转换回 utf-8 字符。

def unescape(text):
   """Removes HTML or XML character references 
      and entities from a text string.
   @param text The HTML (or XML) source text.
   @return The plain text, as a Unicode string, if necessary.
   from Fredrik Lundh
   2008-01-03: input only unicode characters string.
   http://effbot.org/zone/re-sub.htm#unescape-html
   """
   def fixup(m):
      text = m.group(0)
      if text[:2] == "&#":
         # character reference
         try:
            if text[:3] == "&#x":
               return unichr(int(text[3:-1], 16))
            else:
               return unichr(int(text[2:-1]))
         except ValueError:
            print "Value Error"
            pass
      else:
         # named entity
         # reescape the reserved characters.
         try:
            if text[1:-1] == "amp":
               text = "&amp;amp;"
            elif text[1:-1] == "gt":
               text = "&amp;gt;"
            elif text[1:-1] == "lt":
               text = "&amp;lt;"
            else:
               print text[1:-1]
               text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
         except KeyError:
            print "keyerror"
            pass
      return text # leave as is
   return re.sub("&#?\w+;", fixup, text)

【讨论】:

  • 为什么这个答案被修改了?对我来说似乎很有用。
  • 因为这个人想要 unicode 字符而不是 utf-8 字符。我猜:)
【解决方案5】:

不确定为什么 Stack Overflow 线程不包含“;”在搜索/替换中(即 lambda m: '%d*;*')如果不这样做,BeautifulSoup 可能会出错,因为相邻字符可以解释为 HTML 代码的一部分(即 'B 表示 'Blackout)。

这对我来说效果更好:

import re
from BeautifulSoup import BeautifulSoup

html_string='<a href="/cgi-bin/article.cgi?f=/c/a/2010/12/13/BA3V1GQ1CI.DTL"title="">&#x27;Blackout in a can; on some shelves despite ban</a>'

hexentityMassage = [(re.compile('&#x([^;]+);'), 
lambda m: '&#%d;' % int(m.group(1), 16))]

soup = BeautifulSoup(html_string, 
convertEntities=BeautifulSoup.HTML_ENTITIES, 
markupMassage=hexentityMassage)
  1. int(m.group(1), 16) 将数字(以 base-16 指定)格式转换回整数。
  2. m.group(0) 返回整个匹配,m.group(1) 返回正则表达式捕获组
  3. 基本上使用markupMessage是一样的:
    html_string = re.sub('([^;]+);', lambda m: '%d;' % int(m.group(1), 16), html_string)

【讨论】:

  • 感谢您发现错误。我已经编辑了my answer
【解决方案6】:

另一种选择,如果你有 lxml:

>>> import lxml.html
>>> lxml.html.fromstring('&#x01ce').text
u'\u01ce'

【讨论】:

  • 不过要小心,因为如果没有特殊字符,这也可以返回str 类型的对象。
  • 一切都失败时的最佳解决方案,只有 lxml 来救援。 :)
【解决方案7】:

标准库自己的 HTMLParser 有一个未记录的函数 unescape(),它完全按照您的想法执行:

直到 Python 3.4:

import HTMLParser
h = HTMLParser.HTMLParser()
h.unescape('&copy; 2010') # u'\xa9 2010'
h.unescape('&#169; 2010') # u'\xa9 2010'

Python 3.4+:

import html
html.unescape('&copy; 2010') # u'\xa9 2010'
html.unescape('&#169; 2010') # u'\xa9 2010'

【讨论】:

  • Python 的 HTMLParser 文档中没有记录此方法,并且源代码中有一条注释说明它是供内部使用的。但是,它在 Python 2.6 到 2.7 中的工作方式与处理类似,并且可能是目前最好的解决方案。在 2.6 版之前,它只会解码像 &amp;amp;&amp;gt; 这样的命名实体。
  • 在 Python 3.4+ 中暴露为 html.unescape() 函数
  • 这引发UnicodeDecodeError 带有utf-8 字符串。您必须先decode('utf-8') 或使用xml.sax.saxutils.unescape
【解决方案8】:

如果您使用的是 Python 3.4 或更高版本,则只需使用 html.unescape

import html

s = html.unescape(s)

【讨论】:

    【解决方案9】:

    另一个解决方案是内置库 xml.sax.saxutils(适用于 html 和 xml)。但是,它只会转换 &gt、&amp 和 &lt。

    from xml.sax.saxutils import unescape
    
    escaped_text = unescape(text_to_escape)
    

    【讨论】:

      【解决方案10】:

      这是dF's answer的Python 3版本:

      import re
      import html.entities
      
      def unescape(text):
          """
          Removes HTML or XML character references and entities from a text string.
      
          :param text:    The HTML (or XML) source text.
          :return:        The plain text, as a Unicode string, if necessary.
          """
          def fixup(m):
              text = m.group(0)
              if text[:2] == "&#":
                  # character reference
                  try:
                      if text[:3] == "&#x":
                          return chr(int(text[3:-1], 16))
                      else:
                          return chr(int(text[2:-1]))
                  except ValueError:
                      pass
              else:
                  # named entity
                  try:
                      text = chr(html.entities.name2codepoint[text[1:-1]])
                  except KeyError:
                      pass
              return text # leave as is
          return re.sub("&#?\w+;", fixup, text)
      

      主要变化涉及htmlentitydefs,即现在的html.entitiesunichr,即现在的chr。看到这个Python 3 porting guide

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-03
      • 2023-03-30
      • 2012-11-27
      • 2016-02-25
      • 1970-01-01
      相关资源
      最近更新 更多