diff --git a/Lib/html/parser.py b/Lib/html/parser.py index c2c7f6bf5da..3f68e189c4c 100644 --- a/Lib/html/parser.py +++ b/Lib/html/parser.py @@ -367,13 +367,16 @@ class HTMLParser(_markupbase.ParserBase): return s def replaceEntities(s): s = s.groups()[0] - if s[0] == "#": - s = s[1:] - if s[0] in ['x','X']: - c = int(s[1:], 16) - else: - c = int(s) - return chr(c) + try: + if s[0] == "#": + s = s[1:] + if s[0] in ['x','X']: + c = int(s[1:], 16) + else: + c = int(s) + return chr(c) + except ValueError: + return '&#'+ s +';' else: # Cannot use name2codepoint directly, because HTMLParser # supports apos, which is not part of HTML 4 diff --git a/Lib/test/test_htmlparser.py b/Lib/test/test_htmlparser.py index e982218dba1..661d41dce9c 100755 --- a/Lib/test/test_htmlparser.py +++ b/Lib/test/test_htmlparser.py @@ -319,6 +319,10 @@ DOCTYPE html [ self._run_check("", [ ("starttag", "html", [("foo", "\u20AC&aa&unsupported;")]) ]) + def test_unescape_function(self): + p = html.parser.HTMLParser() + self.assertEqual(p.unescape('&#bad;'),'&#bad;') + self.assertEqual(p.unescape('&'),'&') def test_main():