diff --git a/Lib/html/parser.py b/Lib/html/parser.py --- a/Lib/html/parser.py +++ b/Lib/html/parser.py @@ -184,7 +184,17 @@ elif startswith(" or + # . When strict is True an + # error is raised, when it's False they will be considered + # as bogus comments and parsed (see parse_bogus_comment). + if self.strict: + k = self.parse_declaration(i) + else: + try: + k = self.parse_declaration(i) + except HTMLParseError: + k = self.parse_bogus_comment(i) elif (i + 1) < n: self.handle_data("<") k = i + 1 @@ -256,6 +266,19 @@ i = self.updatepos(i, n) self.rawdata = rawdata[i:] + # Internal -- parse bogus comment, return length or -1 if not terminated + # see http://www.w3.org/TR/html5/tokenization.html#bogus-comment-state + def parse_bogus_comment(self, i, report=1): + rawdata = self.rawdata + if rawdata[i:i+2] != '', i+2) + if pos == -1: + return -1 + if report: + self.handle_comment(rawdata[i+2: pos]) + return pos + 1 + # Internal -- parse processing instr, return end or -1 if not terminated def parse_pi(self, i): rawdata = self.rawdata diff --git a/Lib/test/test_htmlparser.py b/Lib/test/test_htmlparser.py --- a/Lib/test/test_htmlparser.py +++ b/Lib/test/test_htmlparser.py @@ -426,6 +426,19 @@ # see #12888 self.assertEqual(p.unescape('{ ' * 1050), '{ ' * 1050) + def test_broken_comments(self): + html = ('' + '' + '' + '') + expected = [ + ('comment', ' not really a comment '), + ('comment', ' not a comment either --'), + ('comment', ' -- close enough --'), + ('comment', ' <-- this one is supposed to be an empty comment') + ] + self._run_check(html, expected) + def test_broken_condcoms(self): # these condcoms are missing the '--' after '' html = ('broken condcom'