解码 Python 字符串中的 HTML 实体?
- 2024-11-25 08:50:00
- admin 原创
- 199
问题描述:
我正在使用 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
我怎样才能解码中的 HTML 实体text
以获取"£682m"
而不是"£682m"
。
解决方案 1:
Python 3.4+
使用html.unescape()
:
import html
print(html.unescape('£682m'))
FYIhtml.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
解决方案 2:
Beautiful Soup 处理实体转换。在 Beautiful Soup 3 中,您需要指定构造函数convertEntities
的参数BeautifulSoup
(请参阅存档文档的“实体转换”部分)。在 Beautiful Soup 4 中,实体会自动解码。
美麗鹹鸳鸯汤3
>>> from BeautifulSoup import BeautifulSoup
>>> BeautifulSoup("<p>£682m</p>",
... convertEntities=BeautifulSoup.HTML_ENTITIES)
<p>£682m</p>
美麗的汤 4
>>> from bs4 import BeautifulSoup
>>> BeautifulSoup("<p>£682m</p>")
<html><body><p>£682m</p></body></html>
解决方案 3:
您可以使用 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
解决方案 4:
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>
解决方案 5:
我遇到了类似的编码问题。我使用了 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 文档
解决方案 6:
import html
myHtml = "<body><h1> How to use html.unescape() in Python </h1></body>"
encodedHtml = html.escape(myHtml)
print("Encoded HTML: ", encodedHtml)
decodedHtml = html.unescape(encodedHtml)
print("Decoded HTML: ", decodedHtml)
输出:
Encoded HTML: <body><h1> How to use html.unescape() in Python </h1></body>
Decoded HTML: <body><h1> How to use html.unescape() in Python </h1></body>
演示
解决方案 7:
这可能与此无关。但要从整个文档中消除这些 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