330

我正在用 Beautiful Soup 3 解析一些 HTML,但它包含 Beautiful Soup 3 不会自动为我解码的 HTML 实体:

>>> from BeautifulSoup import BeautifulSoup

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

>>> print text
&pound;682m

如何解码 HTML 实体text以获取"£682m"而不是"&pound;682m".

4

6 回答 6

647

Python 3.4+

使用html.unescape()

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

FYIhtml.parser.HTMLParser.unescape已被弃用,并且应该在 3.5 中删除,尽管它被错误地留在了。它将很快从语言中删除。


Python 2.6-3.3

您可以HTMLParser.unescape()从标准库中使用:

>>> 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

您还可以使用six兼容性库来简化导入:

>>> from six.moves.html_parser import HTMLParser
>>> h = HTMLParser()
>>> print(h.unescape('&pound;682m'))
£682m
于 2010-01-18T16:17:50.437 回答
71

Beautiful Soup 处理实体转换。在 Beautiful Soup 3 中,您需要指定构造函数的convertEntities参数BeautifulSoup(请参阅存档文档的“实体转换”部分)。在 Beautiful Soup 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>
于 2010-01-18T16:19:14.723 回答
16

您可以使用 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
于 2016-08-09T08:52:54.480 回答
6

Beautiful Soup 4 允许您为输出设置格式化程序

如果你传入formatter=None,Beautiful Soup 在输出时根本不会修改字符串。这是最快的选择,但它可能会导致 Beautiful Soup 生成无效的 HTML/XML,如以下示例所示:

print(soup.prettify(formatter=None))
# <html>
#  <body>
#   <p>
#    Il a dit <<Sacré bleu!>>
#   </p>
#  </body>
# </html>

link_soup = BeautifulSoup('<a href="http://example.com/?foo=val1&bar=val2">A link</a>')
print(link_soup.a.encode(formatter=None))
# <a href="http://example.com/?foo=val1&bar=val2">A link</a>
于 2014-01-14T10:03:44.137 回答
1

我有一个类似的编码问题。我使用了 normalize() 方法。将我的数据框导出到另一个目录中的 .html 文件时,使用 pandas .to_html() 方法出现 Unicode 错误。我最终这样做了,它奏效了......

    import unicodedata 

数据框对象可以是任何你喜欢的对象,我们称之为表......

    table = pd.DataFrame(data,columns=['Name','Team','OVR / POT'])
    table.index+= 1

编码表数据,以便我们可以将其导出到模板文件夹中的 .html 文件(这可以是您希望的任何位置 :))

     #this is where the magic happens
     html_data=unicodedata.normalize('NFKD',table.to_html()).encode('ascii','ignore')

将标准化字符串导出到 html 文件

    file = open("templates/home.html","w") 

    file.write(html_data) 

    file.close() 

参考:unicodedata 文档

于 2020-04-02T21:03:50.733 回答
-5

这可能与这里无关。但是要从整个文档中消除这些 html 实体,您可以执行以下操作:(假设 document = page 并请原谅草率的代码,但是如果您对如何使它变得更好有想法,我全神贯注 - 我是新手这)。

import re
import HTMLParser

regexp = "&.+?;" 
list_of_html = re.findall(regexp, page) #finds all html entites in page
for e in list_of_html:
    h = HTMLParser.HTMLParser()
    unescaped = h.unescape(e) #finds the unescaped value of the html entity
    page = page.replace(e, unescaped) #replaces html entity with unescaped value
于 2012-12-18T18:28:55.157 回答