我正在进行一些网页抓取工作,网站经常使用HTML实体来表示非ASCII字符。Python是否有一种工具可以接受一个带有HTML实体的字符串并返回一个Unicode类型?
例如:
我得到的结果是:
ǎ
该实体代表带声调的 "ǎ"。在二进制中,这表示为 16 位的 01ce。我想将 HTML 实体转换为值 u'\u01ce'
。
标准库自带的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'
&
或 >
这样的命名实体。 - Aram Dulyanhtml.unescape()
函数被公开为转义HTML字符串的方法。 - jfsUnicodeDecodeError
。您必须首先进行decode('utf-8')
或使用xml.sax.saxutils.unescape
。 - StanPython有一个名为htmlentitydefs的模块,但其中并没有包含解码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)
&
这样的字符,是吗? - jnns使用内置的unichr
函数 -- 不需要使用BeautifulSoup:
>>> entity = 'ǎ'
>>> unichr(int(entity[3:],16))
u'\u01ce'
try...catch
捕获异常。 - smci如果您使用的是Python 3.4或更高版本,您可以直接使用html.unescape
函数:
import html
s = html.unescape(s)
如果你有lxml,可以尝试另一种方法:
>>> import lxml.html
>>> lxml.html.fromstring('ǎ').text
u'\u01ce'
str
类型的对象。 - pintochBeautifulSoup
无法转换以十六进制形式编写的实体。可以通过以下方式解决: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'
编辑:
unescape()
函数由 @dF 提到,它使用了 htmlentitydefs
标准模块和 unichr()
,在这种情况下可能更加适合。
HTMLParser.HTMLParser().unescape()
hack适用于您,否则使用BeautifulSoup可能比手动定义unescape()更好(使用纯Python库的供应商与函数的复制粘贴)。 - jfsdef 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)
from xml.sax.saxutils import unescape
escaped_text = unescape(text_to_escape)
这是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 迁移指南。html.unescape()
函数;何必自己费力做一些重复的事情呢? - Martijn Pietershtml.entities.entitydefs["apos"]
不存在,而 html.unescape('can't')
会生成 "can't"
,其中使用了 U+0027 ('
) 而非正常的 U+2019 (’
)(或者取决于您遵循的参数而使用的 U+02BC)。但根据字符实体引用,我想这是有意为之的。 - Jens