如何使用 Python 替换 HTML 转义字符? [复制]
Posted
技术标签:
【中文标题】如何使用 Python 替换 HTML 转义字符? [复制]【英文标题】:How can I use Python to replace HTML escape characters? [duplicate] 【发布时间】:2012-07-09 11:56:27 【问题描述】:可能重复:Decode html entities in Python string?
我有一个充满 HTML 转义字符的字符串,例如 "
、”
和 —
。
是否有任何 Python 库提供可靠的方法让我用它们各自的实际字符替换所有这些转义字符?
例如,我希望将所有"
s 替换为“s”。
【问题讨论】:
string.replace 使用美丽的汤:lxml.de/elementsoup.html 【参考方案1】:你想用这个:
try:
from html.parser import HTMLParser # Python 3
except ModuleNotFoundError:
from HTMLParser import HTMLParser # Python 2
parser = HTMLParser()
html_decoded_string = parser.unescape(html_encoded_string)
我也看到了对 BeautifulSoup 的喜爱
from BeautifulSoup import BeautifulSoup
html_decoded_string = BeautifulSoup(html_encoded_string, convertEntities=BeautifulSoup.HTML_ENTITIES)
这些现有问题也重复:
Decode HTML entities in Python string?
Decoding HTML entities with Python
Decoding HTML Entities With Python
【讨论】:
如果你知道它是重复的,为什么不标记而不是回答(除了代表)? 当人们不花时间寻找他们问题的现有答案时,这很烦人,尤其是在这种情况下 - 当有这么多精确的副本时。但是,我觉得社区有时会过度标榜。如果我们误解了这个问题并且它真的不是重复的怎么办?如果我回答这个问题引发了一个有意义的对话/线程,将问题和答案引向不同的方向怎么办?此外,它与声誉无关,一旦问题被关闭或删除,与之相关的声誉可能会被否定...... 我只是试图警告你 *** 上普遍接受的行为规范。如果您似乎有点在意,我会查找有关此的 Meta question,但我想您可以自己找到它,如果您有兴趣。我不想为此争论,我只是信使,随你所愿:)。 使用beautifulsoup4==4.6.0
和py3,这应该是pip install beautifulsoup4
,然后是from bs4 import BeautifulSoup; html_decoded_string = BeautifulSoup(x, "lxml"); print(html_decoded_string.string)
在 Python 3 中,这应该是 from html.parser import HTMLParser
。以上是关于如何使用 Python 替换 HTML 转义字符? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
为re.sub替换参数转义Python正则表达式字符串? [复制]