Python-用Python字符串解码HTML实体?
我正在使用Beautiful Soup 3解析一些HTML,但是它包含HTML实体,Beautiful Soup 3不会自动为我解码:
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup("<p>£682m</p>")
>>> text = soup.find("p").string
>>> print text
£682m
如何解码HTML实体text以获得"£682m"
而不是"£682m"
。
-
Python 3.4以上
用途
html.unescape()
:import html print(html.unescape('£682m'))
FYI html.parser.HTMLParser.unescape已弃用,并且应该在3.5中删除,尽管它是错误地保留的。它将很快从语言中删除。
Python 2.6-3.3
你可以
HTMLParser.unescape()
从标准库中使用:- 对于python 2.6-2.7 HTMLParser
- 对于Python 3 html.parser
>>> try: ... # Python 2.6-2.7 ... from HTMLParser import HTMLParser ... except ImportError: ... # Python 3 ... from html.parser import HTMLParser ... >>> h = HTMLParser() >>> print(h.unescape('£682m')) £682m
你还可以使用six兼容性库来简化导入:
>>> from six.moves.html_parser import HTMLParser >>> h = HTMLParser() >>> print(h.unescape('£682m')) £682m