我正在使用 Beautiful Soup 3 解析一些 HTML,但它包含 Beautiful Soup 3 不会自动为我解码的 HTML 实体:
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup("<p>£682m</p>")
>>> text = soup.find("p").string
>>> print text
£682m
如何解码
text
中的 HTML 实体以获得 "£682m"
而不是 "£682m"
。
html.unescape()
:
import html
print(html.unescape('£682m'))
仅供参考
html.parser.HTMLParser.unescape
已被弃用,并且 应该在 3.5 中删除,尽管它被错误地保留了。它将很快从语言中删除。
您可以使用标准库中的
HTMLParser.unescape()
:
HTMLParser
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
Beautiful Soup 处理实体转换。在 Beautiful Soup 3 中,您需要为
convertEntities
构造函数指定 BeautifulSoup
参数(请参阅存档文档的 'Entity Conversion' 部分)。在 Beautiful Soup 4 中,实体会自动解码。
>>> from BeautifulSoup import BeautifulSoup
>>> BeautifulSoup("<p>£682m</p>",
... convertEntities=BeautifulSoup.HTML_ENTITIES)
<p>£682m</p>
>>> from bs4 import BeautifulSoup
>>> BeautifulSoup("<p>£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("£682m")
Out[203]: u'\xa3682m'
In [204]: print replace_entities("£682m")
£682m
Beautiful Soup 4 允许您为输出设置格式化程序
如果传入
,Beautiful Soup 不会修改字符串 完全取决于输出。这是最快的选择,但可能会导致 Beautiful Soup 生成无效的 HTML/XML,如以下示例所示:formatter=None
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>
我有类似的编码问题。我使用了 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()
这可能与这里无关。但是要从整个文档中消除这些 html 实体,您可以执行以下操作:(假设文档=页面,请原谅草率的代码,但如果您有如何改进的想法,我洗耳恭听 - 我是新手这个)。
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