PageRenderTime 47ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/Python/system/HTMLParser.py

https://bitbucket.org/cwalther/moulscript-dlanor
Python | 382 lines | 345 code | 16 blank | 21 comment | 41 complexity | bc897c0934a18c2bcee2c26a4d87cc58 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-3.0
  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 comment, return end or -1 if not terminated
  181. def parse_comment(self, i, report=1):
  182. rawdata = self.rawdata
  183. assert rawdata[i:i+4] == '<!--', 'unexpected call to parse_comment()'
  184. match = commentclose.search(rawdata, i+4)
  185. if not match:
  186. return -1
  187. if report:
  188. j = match.start()
  189. self.handle_comment(rawdata[i+4: j])
  190. j = match.end()
  191. return j
  192. # Internal -- parse processing instr, return end or -1 if not terminated
  193. def parse_pi(self, i):
  194. rawdata = self.rawdata
  195. assert rawdata[i:i+2] == '<?', 'unexpected call to parse_pi()'
  196. match = piclose.search(rawdata, i+2) # >
  197. if not match:
  198. return -1
  199. j = match.start()
  200. self.handle_pi(rawdata[i+2: j])
  201. j = match.end()
  202. return j
  203. # Internal -- handle starttag, return end or -1 if not terminated
  204. def parse_starttag(self, i):
  205. self.__starttag_text = None
  206. endpos = self.check_for_whole_start_tag(i)
  207. if endpos < 0:
  208. return endpos
  209. rawdata = self.rawdata
  210. self.__starttag_text = rawdata[i:endpos]
  211. # Now parse the data between i+1 and j into a tag and attrs
  212. attrs = []
  213. match = tagfind.match(rawdata, i+1)
  214. assert match, 'unexpected call to parse_starttag()'
  215. k = match.end()
  216. self.lasttag = tag = rawdata[i+1:k].lower()
  217. while k < endpos:
  218. m = attrfind.match(rawdata, k)
  219. if not m:
  220. break
  221. attrname, rest, attrvalue = m.group(1, 2, 3)
  222. if not rest:
  223. attrvalue = None
  224. elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
  225. attrvalue[:1] == '"' == attrvalue[-1:]:
  226. attrvalue = attrvalue[1:-1]
  227. attrvalue = self.unescape(attrvalue)
  228. attrs.append((attrname.lower(), attrvalue))
  229. k = m.end()
  230. end = rawdata[k:endpos].strip()
  231. if end not in (">", "/>"):
  232. lineno, offset = self.getpos()
  233. if "\n" in self.__starttag_text:
  234. lineno = lineno + self.__starttag_text.count("\n")
  235. offset = len(self.__starttag_text) \
  236. - self.__starttag_text.rfind("\n")
  237. else:
  238. offset = offset + len(self.__starttag_text)
  239. self.error("junk characters in start tag: %s"
  240. % `rawdata[k:endpos][:20]`)
  241. if end.endswith('/>'):
  242. # XHTML-style empty tag: <span attr="value" />
  243. self.handle_startendtag(tag, attrs)
  244. else:
  245. self.handle_starttag(tag, attrs)
  246. if tag in self.CDATA_CONTENT_ELEMENTS:
  247. self.set_cdata_mode()
  248. return endpos
  249. # Internal -- check to see if we have a complete starttag; return end
  250. # or -1 if incomplete.
  251. def check_for_whole_start_tag(self, i):
  252. rawdata = self.rawdata
  253. m = locatestarttagend.match(rawdata, i)
  254. if m:
  255. j = m.end()
  256. next = rawdata[j:j+1]
  257. if next == ">":
  258. return j + 1
  259. if next == "/":
  260. if rawdata.startswith("/>", j):
  261. return j + 2
  262. if rawdata.startswith("/", j):
  263. # buffer boundary
  264. return -1
  265. # else bogus input
  266. self.updatepos(i, j + 1)
  267. self.error("malformed empty start tag")
  268. if next == "":
  269. # end of input
  270. return -1
  271. if next in ("abcdefghijklmnopqrstuvwxyz=/"
  272. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
  273. # end of input in or before attribute value, or we have the
  274. # '/' from a '/>' ending
  275. return -1
  276. self.updatepos(i, j)
  277. self.error("malformed start tag")
  278. raise AssertionError("we should not get here!")
  279. # Internal -- parse endtag, return end or -1 if incomplete
  280. def parse_endtag(self, i):
  281. rawdata = self.rawdata
  282. assert rawdata[i:i+2] == "</", "unexpected call to parse_endtag"
  283. match = endendtag.search(rawdata, i+1) # >
  284. if not match:
  285. return -1
  286. j = match.end()
  287. match = endtagfind.match(rawdata, i) # </ + tag + >
  288. if not match:
  289. self.error("bad end tag: %s" % `rawdata[i:j]`)
  290. tag = match.group(1)
  291. self.handle_endtag(tag.lower())
  292. self.clear_cdata_mode()
  293. return j
  294. # Overridable -- finish processing of start+end tag: <tag.../>
  295. def handle_startendtag(self, tag, attrs):
  296. self.handle_starttag(tag, attrs)
  297. self.handle_endtag(tag)
  298. # Overridable -- handle start tag
  299. def handle_starttag(self, tag, attrs):
  300. pass
  301. # Overridable -- handle end tag
  302. def handle_endtag(self, tag):
  303. pass
  304. # Overridable -- handle character reference
  305. def handle_charref(self, name):
  306. pass
  307. # Overridable -- handle entity reference
  308. def handle_entityref(self, name):
  309. pass
  310. # Overridable -- handle data
  311. def handle_data(self, data):
  312. pass
  313. # Overridable -- handle comment
  314. def handle_comment(self, data):
  315. pass
  316. # Overridable -- handle declaration
  317. def handle_decl(self, decl):
  318. pass
  319. # Overridable -- handle processing instruction
  320. def handle_pi(self, data):
  321. pass
  322. def unknown_decl(self, data):
  323. self.error("unknown declaration: " + `data`)
  324. # Internal -- helper to remove special character quoting
  325. def unescape(self, s):
  326. if '&' not in s:
  327. return s
  328. s = s.replace("&lt;", "<")
  329. s = s.replace("&gt;", ">")
  330. s = s.replace("&apos;", "'")
  331. s = s.replace("&quot;", '"')
  332. s = s.replace("&amp;", "&") # Must be last
  333. return s