問題描述

我用美麗的湯 3 解析一些 HTML,但它包含了美麗的湯 3 不會為我自動解碼的 HTML 實體:

>>> from BeautifulSoup import BeautifulSoup

>>> soup = BeautifulSoup("<p>&pound;682m</p>")
>>> text = soup.find("p").string

>>> print text
&pound;682m

如何解碼 text 中的 HTML 實體來獲取"£682m"而不是"&pound;682m"

最佳解決方案

Python 3.4+

HTMLParser.unescape 已被棄用,而 was supposed to be removed in 3.5 雖然被遺漏了。它將很快從語言中刪除。而是使用 html.unescape()

import html
print(html.unescape('&pound;682m'))

https://docs.python.org/3/library/html.html#html.unescape


Python 2.6-3.3

您可以使用標準庫中的 HTML 解析器:

>>> try:
...     # Python 2.6-2.7
...     from HTMLParser import HTMLParser
... except ImportError:
...     # Python 3
...     from html.parser import HTMLParser
...
>>> h = HTMLParser()
>>> print(h.unescape('&pound;682m'))
£682m

參見 http://docs.python.org/2/library/htmlparser.html

您還可以使用 six 相容性庫來簡化匯入:

>>> from six.moves.html_parser import HTMLParser
>>> h = HTMLParser()
>>> print(h.unescape('&pound;682m'))
£682m

次佳解決方案

美麗的湯處理實體轉換。在美麗的湯 3 中,您需要為 BeautifulSoup 建構函式指定 convertEntities 引數 (請參閱歸檔檔案的‘Entity Conversion’ 部分) 。美麗的湯 4,實體自動解碼。

美麗的湯 3

>>> from BeautifulSoup import BeautifulSoup
>>> BeautifulSoup("<p>&pound;682m</p>",
...               convertEntities=BeautifulSoup.HTML_ENTITIES)
<p>£682m</p>

美麗的湯 4

>>> from bs4 import BeautifulSoup
>>> BeautifulSoup("<p>&pound;682m</p>")
<html><body><p>£682m</p></body></html>

第三種解決方案

您可以使用 w3lib.html 庫中的 replace_entities

In [202]: from w3lib.html import replace_entities

In [203]: replace_entities("&pound;682m")
Out[203]: u'xa3682m'

In [204]: print replace_entities("&pound;682m")
£682m

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇