Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Decode HTML entities in Python string?

I'm parsing some HTML with Beautiful Soup 3, but it contains HTML entities which Beautiful Soup 3 doesn't automatically decode for me:

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

How can I decode the HTML entities in text to get "682ドルm" instead of "&pound;682m".

Answer*

Draft saved
Draft discarded
Cancel
8
  • 9
    this method doesn't seem to escape characters like "&#8217;" on google app engine, though it works locally on python2.6. It does still decode entities (like &quot;) at least Commented Jul 10, 2010 at 14:40
  • How can an undocumented API be deprecated? Edited the answer. Commented Jun 5, 2015 at 18:15
  • @MarkusUnterwaditzer there's no reason that an undocumented method can't be deprecated. This one throws deprecation warnings - see my edit to the answer. Commented Nov 25, 2015 at 15:06
  • 1
    Worth noting for Python 2: Special characters are replaced with their Latin-1 (ISO-8859-1) encoding counterparts. E.g., it may be necessary to h.unescape(s).encode("utf-8"). The docs: """The definition provided here contains all the entities defined by XHTML 1.0 that can be handled using simple textual substitution in the Latin-1 character set (ISO-8859-1)""" Commented Sep 5, 2018 at 15:03
  • 1
    It does not work for 'Don&‌#039;t forget that &‌pi; = 3.14 &‌amp; doesn&‌#039;t equal 3.' WHY is that? Commented May 1, 2020 at 9:15

default

AltStyle によって変換されたページ (->オリジナル) /