在 Python 中将 XML/HTML 实体转换为 Unicode 字符串[重复]
- 2025-01-06 08:32:00
- admin 原创
- 126
问题描述:
我正在做一些网页抓取,网站经常使用 HTML 实体来表示非 ascii 字符。Python 是否有一个实用程序可以接受带有 HTML 实体的字符串并返回 unicode 类型?
例如:
我回复说:
ǎ
表示带音调符号的“ǎ”。在二进制中,这表示为 16 位 01ce。我想将 html 实体转换为值 u'/u01ce'
解决方案 1:
标准库自己的 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'
解决方案 2:
Python 有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)
解决方案 3:
使用内置功能unichr
——BeautifulSoup 不是必需的:
>>> entity = 'ǎ'
>>> unichr(int(entity[3:],16))
u'/u01ce'
解决方案 4:
如果你使用的是 Python 3.4 或更新版本,你可以简单地使用html.unescape
:
import html
s = html.unescape(s)
解决方案 5:
另一种方法是,如果你有 lxml:
>>> import lxml.html
>>> lxml.html.fromstring('ǎ').text
u'/u01ce'
解决方案 6:
您可以在这里找到答案——从网页获取国际字符?
编辑:似乎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'
编辑:
unescape()
@dF提到的函数使用 htmlentitydefs
标准模块,unichr()
在这种情况下可能更合适。
解决方案 7:
这个函数应该可以帮助您正确地将实体转换回 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)
解决方案 8:
不确定为什么 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)
int(m.group(1), 16) 将数字(以 16 为基数指定)格式转换回整数。
m.group(0) 返回整个匹配,m.group(1) 返回正则表达式捕获组
基本上使用 markupMessage 与以下相同:
html_string = re.sub('(1+);', lambda m: '%d;' % int(m.group(1), 16), html_string)
解决方案 9:
另一个解决方案是内置库 xml.sax.saxutils(适用于 html 和 xml)。但是,它只能转换 >、& 和 <。
from xml.sax.saxutils import unescape
escaped_text = unescape(text_to_escape)
解决方案 10:
以下是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
that is nowhtml.entities
和unichr
that is now chr
。请参阅此Python 3 移植指南。
- ; ↩
扫码咨询,免费领取项目管理大礼包!