在Python中将XML/HTML实体转换为Unicode字符串

77

我正在进行一些网页抓取工作,网站经常使用HTML实体来表示非ASCII字符。Python是否有一种工具可以接受一个带有HTML实体的字符串并返回一个Unicode类型?

例如:

我得到的结果是:

ǎ

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


如何在Python字符串中解码HTML实体?(https://dev59.com/p3I95IYBdhLWcg3w7SpZ) - jfs
10个回答

61

标准库自带的HTMLParser有一个未记录在案的函数unescape(),它正是你认为的那样:

Python 3.4及以下版本可用:

import HTMLParser
h = HTMLParser.HTMLParser()
h.unescape('© 2010') # u'\xa9 2010'
h.unescape('© 2010') # u'\xa9 2010'

Python 3.4+:

import html
html.unescape('© 2010') # u'\xa9 2010'
html.unescape('© 2010') # u'\xa9 2010'

它也适用于十六进制实体。该实现与@dF的答案中的unescape()函数非常相似。 - jfs
8
这种方法没有在 Python 的 HTMLParser 文档中记录,并且源代码中有一条注释说明它是用于内部使用的。然而,在 Python 2.6 到 2.7 中,它能够非常好地工作,很可能是目前最好的解决方案。在 2.6 版本之前,它只能解码像 &> 这样的命名实体。 - Aram Dulyan
7
在Python 3.4+中,html.unescape()函数被公开为转义HTML字符串的方法。 - jfs
这将对utf-8字符串引发UnicodeDecodeError。您必须首先进行decode('utf-8')或使用xml.sax.saxutils.unescape - Stan


18

使用内置的unichr函数 -- 不需要使用BeautifulSoup:

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

2
但这要求您自动且明确地知道编码的Unicode字符在字符串中的位置 - 而这是无法知道的。而且,当出错时,您需要使用 try...catch 捕获异常。 - smci
在Python3中已经移除了“unichar”,您对该版本有什么建议? - Stefan Collier

18

如果您使用的是Python 3.4或更高版本,您可以直接使用html.unescape函数:

import html

s = html.unescape(s)

16

如果你有lxml,可以尝试另一种方法:

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

要小心,因为如果没有特殊字符,这也可能返回一个str类型的对象。 - pintoch
当所有解决方案都失效时,只有lxml能够拯救。 :) - Mansoor Akram

8
您可以在这里找到答案--如何从网页中获取国际字符? 编辑:似乎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'

编辑:

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


这个解决方案不能处理以下示例:print BeautifulSoup('<html>ǎ</html>', convertEntities=BeautifulSoup.HTML_ENTITIES)它返回相同的HTML实体。 - Cristian
注意:此内容仅适用于BeautifulSoup 3,自2012年以来已被弃用并被视为遗留。 BeautifulSoup 4会自动处理这些HTML实体。 - Martijn Pieters
@MartijnPieters:正确。html.unescape() 是在现代Python中更好的选择。 - jfs
当然可以。如果你只想解码HTML实体,根本不需要使用BeautifulSoup。 - Martijn Pieters
@MartijnPieters:在旧版本的Python中,除非HTMLParser.HTMLParser().unescape() hack适用于您,否则使用BeautifulSoup可能比手动定义unescape()更好(使用纯Python库的供应商与函数的复制粘贴)。 - jfs

5
这是一个函数,它应该帮助您正确获取并将实体转换回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)

3
为什么这个回答被点踩了?我觉得它很有用。 - dariopy
1
因为该人想要Unicode字符而不是UTF-8字符。我猜 :) - karlcow

3

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

以下内容对我更有效:

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) 将十六进制格式的数字转换为整数。
  2. m.group(0) 返回整个匹配结果,m.group(1) 返回正则表达式捕获的组。
  3. 使用 markupMessage 的基本操作与以下操作相同:
    html_string = re.sub('&#x([^;]+);', lambda m: '&#%d;' % int(m.group(1), 16), html_string)

感谢您发现了这个错误。我已经编辑了我的回答 - jfs

1
另一个解决方案是使用内置的库xml.sax.saxutils(适用于HTML和XML)。然而,它只会转换&gt、&amp和&lt。
from xml.sax.saxutils import unescape

escaped_text = unescape(text_to_escape)

0

这是dF的答案的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.entities,以及 unichr 现在是 chr。请参阅 Python 3 迁移指南

在Python 3中,你只需要使用html.unescape()函数;何必自己费力做一些重复的事情呢? - Martijn Pieters
html.entities.entitydefs["apos"] 不存在,而 html.unescape('can&apos;t') 会生成 "can't",其中使用了 U+0027 (') 而非正常的 U+2019 ()(或者取决于您遵循的参数而使用的 U+02BC)。但根据字符实体引用,我想这是有意为之的。 - Jens

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接