]> granicus.if.org Git - python/commitdiff
Fix Issue10759 - HTMLParser.unescape() to handle malform charrefs.
authorSenthil Kumaran <orsenthil@gmail.com>
Tue, 28 Dec 2010 16:05:07 +0000 (16:05 +0000)
committerSenthil Kumaran <orsenthil@gmail.com>
Tue, 28 Dec 2010 16:05:07 +0000 (16:05 +0000)
Lib/HTMLParser.py
Lib/test/test_htmlparser.py

index 7cee47a7c5d7c6a44b712d28154580af5f05daf6..4fdc09aa7631ec2f153f2e969fbbc00fdf1f5a0e 100644 (file)
@@ -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 unichr(c)
+            try:
+                if s[0] == "#":
+                    s = s[1:]
+                    if s[0] in ['x','X']:
+                        c = int(s[1:], 16)
+                    else:
+                        c = int(s)
+                    return unichr(c)
+            except ValueError:
+                return '&#'+s+';'
             else:
                 # Cannot use name2codepoint directly, because HTMLParser supports apos,
                 # which is not part of HTML 4
index c45cf00ecea3cf068097a7f737d0f02a4d87ddf4..717585ca5b9be5c58740cd4c2d31a9d4774c7967 100644 (file)
@@ -320,6 +320,11 @@ DOCTYPE html [
             ("endtag", "p"),
         ])
 
+    def test_unescape_function(self):
+        parser = HTMLParser.HTMLParser()
+        self.assertEqual(parser.unescape('&#bad;'),'&#bad;')
+        self.assertEqual(parser.unescape('&#0038;'),'&')
+
 
 def test_main():
     test_support.run_unittest(HTMLParserTestCase)