_htmlparser.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. """Use the HTMLParser library to parse HTML files that aren't too bad."""
  2. __all__ = [
  3. 'HTMLParserTreeBuilder',
  4. ]
  5. from HTMLParser import (
  6. HTMLParser,
  7. HTMLParseError,
  8. )
  9. import sys
  10. import warnings
  11. # Starting in Python 3.2, the HTMLParser constructor takes a 'strict'
  12. # argument, which we'd like to set to False. Unfortunately,
  13. # http://bugs.python.org/issue13273 makes strict=True a better bet
  14. # before Python 3.2.3.
  15. #
  16. # At the end of this file, we monkeypatch HTMLParser so that
  17. # strict=True works well on Python 3.2.2.
  18. major, minor, release = sys.version_info[:3]
  19. CONSTRUCTOR_TAKES_STRICT = (
  20. major > 3
  21. or (major == 3 and minor > 2)
  22. or (major == 3 and minor == 2 and release >= 3))
  23. from bs4.element import (
  24. CData,
  25. Comment,
  26. Declaration,
  27. Doctype,
  28. ProcessingInstruction,
  29. )
  30. from bs4.dammit import EntitySubstitution, UnicodeDammit
  31. from bs4.builder import (
  32. HTML,
  33. HTMLTreeBuilder,
  34. STRICT,
  35. )
  36. HTMLPARSER = 'html.parser'
  37. class BeautifulSoupHTMLParser(HTMLParser):
  38. def handle_starttag(self, name, attrs):
  39. # XXX namespace
  40. attr_dict = {}
  41. for key, value in attrs:
  42. # Change None attribute values to the empty string
  43. # for consistency with the other tree builders.
  44. if value is None:
  45. value = ''
  46. attr_dict[key] = value
  47. attrvalue = '""'
  48. self.soup.handle_starttag(name, None, None, attr_dict)
  49. def handle_endtag(self, name):
  50. self.soup.handle_endtag(name)
  51. def handle_data(self, data):
  52. self.soup.handle_data(data)
  53. def handle_charref(self, name):
  54. # XXX workaround for a bug in HTMLParser. Remove this once
  55. # it's fixed.
  56. if name.startswith('x'):
  57. real_name = int(name.lstrip('x'), 16)
  58. elif name.startswith('X'):
  59. real_name = int(name.lstrip('X'), 16)
  60. else:
  61. real_name = int(name)
  62. try:
  63. data = unichr(real_name)
  64. except (ValueError, OverflowError), e:
  65. data = u"\N{REPLACEMENT CHARACTER}"
  66. self.handle_data(data)
  67. def handle_entityref(self, name):
  68. character = EntitySubstitution.HTML_ENTITY_TO_CHARACTER.get(name)
  69. if character is not None:
  70. data = character
  71. else:
  72. data = "&%s;" % name
  73. self.handle_data(data)
  74. def handle_comment(self, data):
  75. self.soup.endData()
  76. self.soup.handle_data(data)
  77. self.soup.endData(Comment)
  78. def handle_decl(self, data):
  79. self.soup.endData()
  80. if data.startswith("DOCTYPE "):
  81. data = data[len("DOCTYPE "):]
  82. elif data == 'DOCTYPE':
  83. # i.e. "<!DOCTYPE>"
  84. data = ''
  85. self.soup.handle_data(data)
  86. self.soup.endData(Doctype)
  87. def unknown_decl(self, data):
  88. if data.upper().startswith('CDATA['):
  89. cls = CData
  90. data = data[len('CDATA['):]
  91. else:
  92. cls = Declaration
  93. self.soup.endData()
  94. self.soup.handle_data(data)
  95. self.soup.endData(cls)
  96. def handle_pi(self, data):
  97. self.soup.endData()
  98. if data.endswith("?") and data.lower().startswith("xml"):
  99. # "An XHTML processing instruction using the trailing '?'
  100. # will cause the '?' to be included in data." - HTMLParser
  101. # docs.
  102. #
  103. # Strip the question mark so we don't end up with two
  104. # question marks.
  105. data = data[:-1]
  106. self.soup.handle_data(data)
  107. self.soup.endData(ProcessingInstruction)
  108. class HTMLParserTreeBuilder(HTMLTreeBuilder):
  109. is_xml = False
  110. features = [HTML, STRICT, HTMLPARSER]
  111. def __init__(self, *args, **kwargs):
  112. if CONSTRUCTOR_TAKES_STRICT:
  113. kwargs['strict'] = False
  114. self.parser_args = (args, kwargs)
  115. def prepare_markup(self, markup, user_specified_encoding=None,
  116. document_declared_encoding=None):
  117. """
  118. :return: A 4-tuple (markup, original encoding, encoding
  119. declared within markup, whether any characters had to be
  120. replaced with REPLACEMENT CHARACTER).
  121. """
  122. if isinstance(markup, unicode):
  123. yield (markup, None, None, False)
  124. return
  125. try_encodings = [user_specified_encoding, document_declared_encoding]
  126. dammit = UnicodeDammit(markup, try_encodings, is_html=True)
  127. yield (dammit.markup, dammit.original_encoding,
  128. dammit.declared_html_encoding,
  129. dammit.contains_replacement_characters)
  130. def feed(self, markup):
  131. args, kwargs = self.parser_args
  132. parser = BeautifulSoupHTMLParser(*args, **kwargs)
  133. parser.soup = self.soup
  134. try:
  135. parser.feed(markup)
  136. except HTMLParseError, e:
  137. warnings.warn(RuntimeWarning(
  138. "Python's built-in HTMLParser cannot parse the given document. This is not a bug in Beautiful Soup. The best solution is to install an external parser (lxml or html5lib), and use Beautiful Soup with that parser. See http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser for help."))
  139. raise e
  140. # Patch 3.2 versions of HTMLParser earlier than 3.2.3 to use some
  141. # 3.2.3 code. This ensures they don't treat markup like <p></p> as a
  142. # string.
  143. #
  144. # XXX This code can be removed once most Python 3 users are on 3.2.3.
  145. if major == 3 and minor == 2 and not CONSTRUCTOR_TAKES_STRICT:
  146. import re
  147. attrfind_tolerant = re.compile(
  148. r'\s*((?<=[\'"\s])[^\s/>][^\s/=>]*)(\s*=+\s*'
  149. r'(\'[^\']*\'|"[^"]*"|(?![\'"])[^>\s]*))?')
  150. HTMLParserTreeBuilder.attrfind_tolerant = attrfind_tolerant
  151. locatestarttagend = re.compile(r"""
  152. <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name
  153. (?:\s+ # whitespace before attribute name
  154. (?:[a-zA-Z_][-.:a-zA-Z0-9_]* # attribute name
  155. (?:\s*=\s* # value indicator
  156. (?:'[^']*' # LITA-enclosed value
  157. |\"[^\"]*\" # LIT-enclosed value
  158. |[^'\">\s]+ # bare value
  159. )
  160. )?
  161. )
  162. )*
  163. \s* # trailing whitespace
  164. """, re.VERBOSE)
  165. BeautifulSoupHTMLParser.locatestarttagend = locatestarttagend
  166. from html.parser import tagfind, attrfind
  167. def parse_starttag(self, i):
  168. self.__starttag_text = None
  169. endpos = self.check_for_whole_start_tag(i)
  170. if endpos < 0:
  171. return endpos
  172. rawdata = self.rawdata
  173. self.__starttag_text = rawdata[i:endpos]
  174. # Now parse the data between i+1 and j into a tag and attrs
  175. attrs = []
  176. match = tagfind.match(rawdata, i+1)
  177. assert match, 'unexpected call to parse_starttag()'
  178. k = match.end()
  179. self.lasttag = tag = rawdata[i+1:k].lower()
  180. while k < endpos:
  181. if self.strict:
  182. m = attrfind.match(rawdata, k)
  183. else:
  184. m = attrfind_tolerant.match(rawdata, k)
  185. if not m:
  186. break
  187. attrname, rest, attrvalue = m.group(1, 2, 3)
  188. if not rest:
  189. attrvalue = None
  190. elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
  191. attrvalue[:1] == '"' == attrvalue[-1:]:
  192. attrvalue = attrvalue[1:-1]
  193. if attrvalue:
  194. attrvalue = self.unescape(attrvalue)
  195. attrs.append((attrname.lower(), attrvalue))
  196. k = m.end()
  197. end = rawdata[k:endpos].strip()
  198. if end not in (">", "/>"):
  199. lineno, offset = self.getpos()
  200. if "\n" in self.__starttag_text:
  201. lineno = lineno + self.__starttag_text.count("\n")
  202. offset = len(self.__starttag_text) \
  203. - self.__starttag_text.rfind("\n")
  204. else:
  205. offset = offset + len(self.__starttag_text)
  206. if self.strict:
  207. self.error("junk characters in start tag: %r"
  208. % (rawdata[k:endpos][:20],))
  209. self.handle_data(rawdata[i:endpos])
  210. return endpos
  211. if end.endswith('/>'):
  212. # XHTML-style empty tag: <span attr="value" />
  213. self.handle_startendtag(tag, attrs)
  214. else:
  215. self.handle_starttag(tag, attrs)
  216. if tag in self.CDATA_CONTENT_ELEMENTS:
  217. self.set_cdata_mode(tag)
  218. return endpos
  219. def set_cdata_mode(self, elem):
  220. self.cdata_elem = elem.lower()
  221. self.interesting = re.compile(r'</\s*%s\s*>' % self.cdata_elem, re.I)
  222. BeautifulSoupHTMLParser.parse_starttag = parse_starttag
  223. BeautifulSoupHTMLParser.set_cdata_mode = set_cdata_mode
  224. CONSTRUCTOR_TAKES_STRICT = True