HTMLParser.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. """A parser for HTML and XHTML."""
  2. # This file is based on sgmllib.py, but the API is slightly different.
  3. # XXX There should be a way to distinguish between PCDATA (parsed
  4. # character data -- the normal case), RCDATA (replaceable character
  5. # data -- only char and entity references and end tags are special)
  6. # and CDATA (character data -- only end tags are special).
  7. import markupbase
  8. import re
  9. # Regular expressions used for parsing
  10. interesting_normal = re.compile('[&<]')
  11. interesting_cdata = re.compile(r'<(/|\Z)')
  12. incomplete = re.compile('&[a-zA-Z#]')
  13. entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')
  14. charref = re.compile('&#(?:[0-9]+|[xX][0-9a-fA-F]+)[^0-9a-fA-F]')
  15. starttagopen = re.compile('<[a-zA-Z]')
  16. piclose = re.compile('>')
  17. commentclose = re.compile(r'--\s*>')
  18. tagfind = re.compile('[a-zA-Z][-.a-zA-Z0-9:_]*')
  19. attrfind = re.compile(
  20. r'\s*([a-zA-Z_][-.:a-zA-Z_0-9]*)(\s*=\s*'
  21. r'(\'[^\']*\'|"[^"]*"|[-a-zA-Z0-9./,:;+*%?!&$\(\)_#=~@]*))?')
  22. locatestarttagend = re.compile(r"""
  23. <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name
  24. (?:\s+ # whitespace before attribute name
  25. (?:[a-zA-Z_][-.:a-zA-Z0-9_]* # attribute name
  26. (?:\s*=\s* # value indicator
  27. (?:'[^']*' # LITA-enclosed value
  28. |\"[^\"]*\" # LIT-enclosed value
  29. |[^'\">\s]+ # bare value
  30. )
  31. )?
  32. )
  33. )*
  34. \s* # trailing whitespace
  35. """, re.VERBOSE)
  36. endendtag = re.compile('>')
  37. endtagfind = re.compile('</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
  38. class HTMLParseError(Exception):
  39. """Exception raised for all parse errors."""
  40. def __init__(self, msg, position=(None, None)):
  41. assert msg
  42. self.msg = msg
  43. self.lineno = position[0]
  44. self.offset = position[1]
  45. def __str__(self):
  46. result = self.msg
  47. if self.lineno is not None:
  48. result = result + ", at line %d" % self.lineno
  49. if self.offset is not None:
  50. result = result + ", column %d" % (self.offset + 1)
  51. return result
  52. class HTMLParser(markupbase.ParserBase):
  53. """Find tags and other markup and call handler functions.
  54. Usage:
  55. p = HTMLParser()
  56. p.feed(data)
  57. ...
  58. p.close()
  59. Start tags are handled by calling self.handle_starttag() or
  60. self.handle_startendtag(); end tags by self.handle_endtag(). The
  61. data between tags is passed from the parser to the derived class
  62. by calling self.handle_data() with the data as argument (the data
  63. may be split up in arbitrary chunks). Entity references are
  64. passed by calling self.handle_entityref() with the entity
  65. reference as the argument. Numeric character references are
  66. passed to self.handle_charref() with the string containing the
  67. reference as the argument.
  68. """
  69. CDATA_CONTENT_ELEMENTS = ("script", "style")
  70. def __init__(self):
  71. """Initialize and reset this instance."""
  72. self.reset()
  73. def reset(self):
  74. """Reset this instance. Loses all unprocessed data."""
  75. self.rawdata = ''
  76. self.lasttag = '???'
  77. self.interesting = interesting_normal
  78. markupbase.ParserBase.reset(self)
  79. def feed(self, data):
  80. """Feed data to the parser.
  81. Call this as often as you want, with as little or as much text
  82. as you want (may include '\n').
  83. """
  84. self.rawdata = self.rawdata + data
  85. self.goahead(0)
  86. def close(self):
  87. """Handle any buffered data."""
  88. self.goahead(1)
  89. def error(self, message):
  90. raise HTMLParseError(message, self.getpos())
  91. __starttag_text = None
  92. def get_starttag_text(self):
  93. """Return full source of start tag: '<...>'."""
  94. return self.__starttag_text
  95. def set_cdata_mode(self):
  96. self.interesting = interesting_cdata
  97. def clear_cdata_mode(self):
  98. self.interesting = interesting_normal
  99. # Internal -- handle data as far as reasonable. May leave state
  100. # and data to be processed by a subsequent call. If 'end' is
  101. # true, force handling all data as if followed by EOF marker.
  102. def goahead(self, end):
  103. rawdata = self.rawdata
  104. i = 0
  105. n = len(rawdata)
  106. while i < n:
  107. match = self.interesting.search(rawdata, i) # < or &
  108. if match:
  109. j = match.start()
  110. else:
  111. j = n
  112. if i < j: self.handle_data(rawdata[i:j])
  113. i = self.updatepos(i, j)
  114. if i == n: break
  115. startswith = rawdata.startswith
  116. if startswith('<', i):
  117. if starttagopen.match(rawdata, i): # < + letter
  118. k = self.parse_starttag(i)
  119. elif startswith("</", i):
  120. k = self.parse_endtag(i)
  121. elif startswith("<!--", i):
  122. k = self.parse_comment(i)
  123. elif startswith("<?", i):
  124. k = self.parse_pi(i)
  125. elif startswith("<!", i):
  126. k = self.parse_declaration(i)
  127. elif (i + 1) < n:
  128. self.handle_data("<")
  129. k = i + 1
  130. else:
  131. break
  132. if k < 0:
  133. if end:
  134. self.error("EOF in middle of construct")
  135. break
  136. i = self.updatepos(i, k)
  137. elif startswith("&#", i):
  138. match = charref.match(rawdata, i)
  139. if match:
  140. name = match.group()[2:-1]
  141. self.handle_charref(name)
  142. k = match.end()
  143. if not startswith(';', k-1):
  144. k = k - 1
  145. i = self.updatepos(i, k)
  146. continue
  147. else:
  148. break
  149. elif startswith('&', i):
  150. match = entityref.match(rawdata, i)
  151. if match:
  152. name = match.group(1)
  153. self.handle_entityref(name)
  154. k = match.end()
  155. if not startswith(';', k-1):
  156. k = k - 1
  157. i = self.updatepos(i, k)
  158. continue
  159. match = incomplete.match(rawdata, i)
  160. if match:
  161. # match.group() will contain at least 2 chars
  162. if end and match.group() == rawdata[i:]:
  163. self.error("EOF in middle of entity or char ref")
  164. # incomplete
  165. break
  166. elif (i + 1) < n:
  167. # not the end of the buffer, and can't be confused
  168. # with some other construct
  169. self.handle_data("&")
  170. i = self.updatepos(i, i + 1)
  171. else:
  172. break
  173. else:
  174. assert 0, "interesting.search() lied"
  175. # end while
  176. if end and i < n:
  177. self.handle_data(rawdata[i:n])
  178. i = self.updatepos(i, n)
  179. self.rawdata = rawdata[i:]
  180. # Internal -- parse processing instr, return end or -1 if not terminated
  181. def parse_pi(self, i):
  182. rawdata = self.rawdata
  183. assert rawdata[i:i+2] == '<?', 'unexpected call to parse_pi()'
  184. match = piclose.search(rawdata, i+2) # >
  185. if not match:
  186. return -1
  187. j = match.start()
  188. self.handle_pi(rawdata[i+2: j])
  189. j = match.end()
  190. return j
  191. # Internal -- handle starttag, return end or -1 if not terminated
  192. def parse_starttag(self, i):
  193. self.__starttag_text = None
  194. endpos = self.check_for_whole_start_tag(i)
  195. if endpos < 0:
  196. return endpos
  197. rawdata = self.rawdata
  198. self.__starttag_text = rawdata[i:endpos]
  199. # Now parse the data between i+1 and j into a tag and attrs
  200. attrs = []
  201. match = tagfind.match(rawdata, i+1)
  202. assert match, 'unexpected call to parse_starttag()'
  203. k = match.end()
  204. self.lasttag = tag = rawdata[i+1:k].lower()
  205. while k < endpos:
  206. m = attrfind.match(rawdata, k)
  207. if not m:
  208. break
  209. attrname, rest, attrvalue = m.group(1, 2, 3)
  210. if not rest:
  211. attrvalue = None
  212. elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
  213. attrvalue[:1] == '"' == attrvalue[-1:]:
  214. attrvalue = attrvalue[1:-1]
  215. attrvalue = self.unescape(attrvalue)
  216. attrs.append((attrname.lower(), attrvalue))
  217. k = m.end()
  218. end = rawdata[k:endpos].strip()
  219. if end not in (">", "/>"):
  220. lineno, offset = self.getpos()
  221. if "\n" in self.__starttag_text:
  222. lineno = lineno + self.__starttag_text.count("\n")
  223. offset = len(self.__starttag_text) \
  224. - self.__starttag_text.rfind("\n")
  225. else:
  226. offset = offset + len(self.__starttag_text)
  227. self.error("junk characters in start tag: %r"
  228. % (rawdata[k:endpos][:20],))
  229. if end.endswith('/>'):
  230. # XHTML-style empty tag: <span attr="value" />
  231. self.handle_startendtag(tag, attrs)
  232. else:
  233. self.handle_starttag(tag, attrs)
  234. if tag in self.CDATA_CONTENT_ELEMENTS:
  235. self.set_cdata_mode()
  236. return endpos
  237. # Internal -- check to see if we have a complete starttag; return end
  238. # or -1 if incomplete.
  239. def check_for_whole_start_tag(self, i):
  240. rawdata = self.rawdata
  241. m = locatestarttagend.match(rawdata, i)
  242. if m:
  243. j = m.end()
  244. next = rawdata[j:j+1]
  245. if next == ">":
  246. return j + 1
  247. if next == "/":
  248. if rawdata.startswith("/>", j):
  249. return j + 2
  250. if rawdata.startswith("/", j):
  251. # buffer boundary
  252. return -1
  253. # else bogus input
  254. self.updatepos(i, j + 1)
  255. self.error("malformed empty start tag")
  256. if next == "":
  257. # end of input
  258. return -1
  259. if next in ("abcdefghijklmnopqrstuvwxyz=/"
  260. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
  261. # end of input in or before attribute value, or we have the
  262. # '/' from a '/>' ending
  263. return -1
  264. self.updatepos(i, j)
  265. self.error("malformed start tag")
  266. raise AssertionError("we should not get here!")
  267. # Internal -- parse endtag, return end or -1 if incomplete
  268. def parse_endtag(self, i):
  269. rawdata = self.rawdata
  270. assert rawdata[i:i+2] == "</", "unexpected call to parse_endtag"
  271. match = endendtag.search(rawdata, i+1) # >
  272. if not match:
  273. return -1
  274. j = match.end()
  275. match = endtagfind.match(rawdata, i) # </ + tag + >
  276. if not match:
  277. self.error("bad end tag: %r" % (rawdata[i:j],))
  278. tag = match.group(1)
  279. self.handle_endtag(tag.lower())
  280. self.clear_cdata_mode()
  281. return j
  282. # Overridable -- finish processing of start+end tag: <tag.../>
  283. def handle_startendtag(self, tag, attrs):
  284. self.handle_starttag(tag, attrs)
  285. self.handle_endtag(tag)
  286. # Overridable -- handle start tag
  287. def handle_starttag(self, tag, attrs):
  288. pass
  289. # Overridable -- handle end tag
  290. def handle_endtag(self, tag):
  291. pass
  292. # Overridable -- handle character reference
  293. def handle_charref(self, name):
  294. pass
  295. # Overridable -- handle entity reference
  296. def handle_entityref(self, name):
  297. pass
  298. # Overridable -- handle data
  299. def handle_data(self, data):
  300. pass
  301. # Overridable -- handle comment
  302. def handle_comment(self, data):
  303. pass
  304. # Overridable -- handle declaration
  305. def handle_decl(self, decl):
  306. pass
  307. # Overridable -- handle processing instruction
  308. def handle_pi(self, data):
  309. pass
  310. def unknown_decl(self, data):
  311. self.error("unknown declaration: %r" % (data,))
  312. # Internal -- helper to remove special character quoting
  313. def unescape(self, s):
  314. if '&' not in s:
  315. return s
  316. s = s.replace("&lt;", "<")
  317. s = s.replace("&gt;", ">")
  318. s = s.replace("&apos;", "'")
  319. s = s.replace("&quot;", '"')
  320. s = s.replace("&amp;", "&") # Must be last
  321. return s