这个问题在这里已经有答案了:

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

例如:

我回来了:

ǎ

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

有帮助吗?

解决方案

标准库自己的 HTMLParser 有一个未记录的函数 unescape() ,它的作用完全符合您的想法:

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

其他提示

Python 有 html实体定义 模块,但这不包含转义 HTML 实体的函数。

Python 开发者 Fredrik Lundh(elementtree 的作者等)有这样一个函数 在他的网站上, ,适用于十进制、十六进制和命名实体:

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)

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

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

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

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

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

import html

s = html.unescape(s)

你可以在这里找到答案—— 从网页获取国际字符?

编辑: :这好像是 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() 在这种情况下可能更合适。

这个函数应该可以帮助您正确地将实体转换回 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)

不确定为什么堆栈溢出线程不包括';'在搜索/替换中(即拉姆达米:'&#%d*;*') 如果不这样做,BeautifulSoup 可能会呕吐,因为相邻的字符可以被解释为 HTML 代码的一部分(即&#39B 表示&#39停电)。

这对我来说效果更好:

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) 将数字(以 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)

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

from xml.sax.saxutils import unescape

escaped_text = unescape(text_to_escape)

这是Python 3版本 dF的回答:

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 移植指南.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top