【发布时间】:2010-09-08 15:11:59
【问题描述】:
我正在做一些网页抓取,并且网站经常使用 HTML 实体来表示非 ascii 字符。 Python 是否有一个实用程序可以接收带有 HTML 实体的字符串并返回 unicode 类型?
例如:
我回来了:
ǎ
代表带有声调的“ǎ”。在二进制中,这表示为 16 位 01ce。我想将html实体转换成值u'\u01ce'
【问题讨论】:
我正在做一些网页抓取,并且网站经常使用 HTML 实体来表示非 ascii 字符。 Python 是否有一个实用程序可以接收带有 HTML 实体的字符串并返回 unicode 类型?
例如:
我回来了:
ǎ
代表带有声调的“ǎ”。在二进制中,这表示为 16 位 01ce。我想将html实体转换成值u'\u01ce'
【问题讨论】:
你可以在这里找到答案——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>ǎǎ</html>'
print repr(convert(html))
# u'\u01ce\u01ce'
编辑:
@dF 提到的unescape() 函数使用htmlentitydefs 标准模块和unichr() 在这种情况下可能更合适。
【讨论】:
html.unescape() 是现代 Python 的更好选择。
HTMLParser.HTMLParser().unescape() hack 对您有用,否则使用 BeautifulSoup 可能比手动定义 unescape() 更好(供应纯 Python 库与副本-粘贴函数)。
使用内置的unichr -- BeautifulSoup 不是必需的:
>>> entity = 'ǎ'
>>> unichr(int(entity[3:],16))
u'\u01ce'
【讨论】:
try...catch 产生的异常。
unichar 在 python3 中被删除。对那个版本有什么建议吗?
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; 等,是吗?
这个函数可以帮助您正确处理并将实体转换回 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;"
elif text[1:-1] == "gt":
text = "&gt;"
elif text[1:-1] == "lt":
text = "&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)
【讨论】:
不确定为什么 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="">'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)
【讨论】:
另一种选择,如果你有 lxml:
>>> import lxml.html
>>> lxml.html.fromstring('ǎ').text
u'\u01ce'
【讨论】:
str 类型的对象。
标准库自己的 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'
【讨论】:
&amp; 或 &gt; 这样的命名实体。
html.unescape() 函数
UnicodeDecodeError 带有utf-8 字符串。您必须先decode('utf-8') 或使用xml.sax.saxutils.unescape。
如果您使用的是 Python 3.4 或更高版本,则只需使用 html.unescape:
import html
s = html.unescape(s)
【讨论】:
另一个解决方案是内置库 xml.sax.saxutils(适用于 html 和 xml)。但是,它只会转换 >、& 和 <。
from xml.sax.saxutils import unescape
escaped_text = unescape(text_to_escape)
【讨论】:
这是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.entities 和unichr,即现在的chr。看到这个Python 3 porting guide。
【讨论】:
html.unescape();为什么要养狗并自己吠叫?
html.entities.entitydefs["apos"] 不存在,html.unescape('can&apos;t') 产生 "can't" 使用 U+0027 (') 而不是正确的 U+2019 (’)(或 U+ 02BC,取决于您遵循的论点。)。但我想这是根据character entity reference 的意图。