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*

Convert XML/HTML Entities into Unicode String in Python [duplicate]

I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?

For example:

I get back:

ǎ

which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value u'\u01ce'

Answer*

Draft saved
Draft discarded
Cancel
5
  • This solution doesn't work with the example: print BeautifulSoup('<html>&#x01ce;</html>', convertEntities=BeautifulSoup.HTML_ENTITIES) This returns the same HTML entity Commented Sep 11, 2008 at 22:03
  • Note: this only applied to BeautifulSoup 3, deprecated and considered legacy since 2012. BeautifulSoup 4 handles HTML entities like these automatically. Commented Sep 5, 2017 at 7:28
  • @MartijnPieters: correct. html.unescape() is a better option on the modern Python. Commented Sep 5, 2017 at 7:35
  • Absolutely. If all you wanted was to decode HTML entities there is no need to use BeatifulSoup at all. Commented Sep 5, 2017 at 7:35
  • @MartijnPieters: on old Python versions, unless HTMLParser.HTMLParser().unescape() hack worked for you, using BeautifulSoup might be a better alternative than defining unescape() by hand (vendoring a pure Python lib vs. a copy-paste of the function). Commented Sep 5, 2017 at 7:42

default

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