【问题标题】:How can I use Python to replace HTML escape characters? [duplicate]如何使用 Python 替换 HTML 转义字符? [复制]
【发布时间】:2012-07-09 11:56:27
【问题描述】:

可能重复:
Decode HTML entities in Python string?

我有一个充满 HTML 转义字符的字符串,例如 "”—

是否有任何 Python 库提供可靠的方法让我用它们各自的实际字符替换所有这些转义字符?

例如,我希望将所有"s 替换为“s”。

【问题讨论】:

标签: python


【解决方案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

【讨论】:

  • 如果你知道它是重复的,为什么不标记而不是回答(除了代表)?
  • 当人们不花时间寻找他们问题的现有答案时,这很烦人,尤其是在这种情况下 - 当有这么多精确的副本时。但是,我觉得社区有时会过度标榜。如果我们误解了这个问题并且它真的不是重复的怎么办?如果我回答这个问题引发了一个有意义的对话/线程,将问题和答案引向不同的方向怎么办?此外,它与声誉无关,一旦问题被关闭或删除,与之相关的声誉可能会被否定......
  • 我只是试图警告你 StackOverflow 上普遍接受的行为规范。如果您似乎有点在意,我会查找有关此的 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
猜你喜欢
  • 2016-06-27
  • 1970-01-01
  • 1970-01-01
  • 2016-05-27
  • 1970-01-01
  • 2016-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多