htmllib.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. """HTML 2.0 parser.
  2. See the HTML 2.0 specification:
  3. http://www.w3.org/hypertext/WWW/MarkUp/html-spec/html-spec_toc.html
  4. """
  5. from warnings import warnpy3k
  6. warnpy3k("the htmllib module has been removed in Python 3.0",
  7. stacklevel=2)
  8. del warnpy3k
  9. import sgmllib
  10. from formatter import AS_IS
  11. __all__ = ["HTMLParser", "HTMLParseError"]
  12. class HTMLParseError(sgmllib.SGMLParseError):
  13. """Error raised when an HTML document can't be parsed."""
  14. class HTMLParser(sgmllib.SGMLParser):
  15. """This is the basic HTML parser class.
  16. It supports all entity names required by the XHTML 1.0 Recommendation.
  17. It also defines handlers for all HTML 2.0 and many HTML 3.0 and 3.2
  18. elements.
  19. """
  20. from htmlentitydefs import entitydefs
  21. def __init__(self, formatter, verbose=0):
  22. """Creates an instance of the HTMLParser class.
  23. The formatter parameter is the formatter instance associated with
  24. the parser.
  25. """
  26. sgmllib.SGMLParser.__init__(self, verbose)
  27. self.formatter = formatter
  28. def error(self, message):
  29. raise HTMLParseError(message)
  30. def reset(self):
  31. sgmllib.SGMLParser.reset(self)
  32. self.savedata = None
  33. self.isindex = 0
  34. self.title = None
  35. self.base = None
  36. self.anchor = None
  37. self.anchorlist = []
  38. self.nofill = 0
  39. self.list_stack = []
  40. # ------ Methods used internally; some may be overridden
  41. # --- Formatter interface, taking care of 'savedata' mode;
  42. # shouldn't need to be overridden
  43. def handle_data(self, data):
  44. if self.savedata is not None:
  45. self.savedata = self.savedata + data
  46. else:
  47. if self.nofill:
  48. self.formatter.add_literal_data(data)
  49. else:
  50. self.formatter.add_flowing_data(data)
  51. # --- Hooks to save data; shouldn't need to be overridden
  52. def save_bgn(self):
  53. """Begins saving character data in a buffer instead of sending it
  54. to the formatter object.
  55. Retrieve the stored data via the save_end() method. Use of the
  56. save_bgn() / save_end() pair may not be nested.
  57. """
  58. self.savedata = ''
  59. def save_end(self):
  60. """Ends buffering character data and returns all data saved since
  61. the preceding call to the save_bgn() method.
  62. If the nofill flag is false, whitespace is collapsed to single
  63. spaces. A call to this method without a preceding call to the
  64. save_bgn() method will raise a TypeError exception.
  65. """
  66. data = self.savedata
  67. self.savedata = None
  68. if not self.nofill:
  69. data = ' '.join(data.split())
  70. return data
  71. # --- Hooks for anchors; should probably be overridden
  72. def anchor_bgn(self, href, name, type):
  73. """This method is called at the start of an anchor region.
  74. The arguments correspond to the attributes of the <A> tag with
  75. the same names. The default implementation maintains a list of
  76. hyperlinks (defined by the HREF attribute for <A> tags) within
  77. the document. The list of hyperlinks is available as the data
  78. attribute anchorlist.
  79. """
  80. self.anchor = href
  81. if self.anchor:
  82. self.anchorlist.append(href)
  83. def anchor_end(self):
  84. """This method is called at the end of an anchor region.
  85. The default implementation adds a textual footnote marker using an
  86. index into the list of hyperlinks created by the anchor_bgn()method.
  87. """
  88. if self.anchor:
  89. self.handle_data("[%d]" % len(self.anchorlist))
  90. self.anchor = None
  91. # --- Hook for images; should probably be overridden
  92. def handle_image(self, src, alt, *args):
  93. """This method is called to handle images.
  94. The default implementation simply passes the alt value to the
  95. handle_data() method.
  96. """
  97. self.handle_data(alt)
  98. # --------- Top level elememts
  99. def start_html(self, attrs): pass
  100. def end_html(self): pass
  101. def start_head(self, attrs): pass
  102. def end_head(self): pass
  103. def start_body(self, attrs): pass
  104. def end_body(self): pass
  105. # ------ Head elements
  106. def start_title(self, attrs):
  107. self.save_bgn()
  108. def end_title(self):
  109. self.title = self.save_end()
  110. def do_base(self, attrs):
  111. for a, v in attrs:
  112. if a == 'href':
  113. self.base = v
  114. def do_isindex(self, attrs):
  115. self.isindex = 1
  116. def do_link(self, attrs):
  117. pass
  118. def do_meta(self, attrs):
  119. pass
  120. def do_nextid(self, attrs): # Deprecated
  121. pass
  122. # ------ Body elements
  123. # --- Headings
  124. def start_h1(self, attrs):
  125. self.formatter.end_paragraph(1)
  126. self.formatter.push_font(('h1', 0, 1, 0))
  127. def end_h1(self):
  128. self.formatter.end_paragraph(1)
  129. self.formatter.pop_font()
  130. def start_h2(self, attrs):
  131. self.formatter.end_paragraph(1)
  132. self.formatter.push_font(('h2', 0, 1, 0))
  133. def end_h2(self):
  134. self.formatter.end_paragraph(1)
  135. self.formatter.pop_font()
  136. def start_h3(self, attrs):
  137. self.formatter.end_paragraph(1)
  138. self.formatter.push_font(('h3', 0, 1, 0))
  139. def end_h3(self):
  140. self.formatter.end_paragraph(1)
  141. self.formatter.pop_font()
  142. def start_h4(self, attrs):
  143. self.formatter.end_paragraph(1)
  144. self.formatter.push_font(('h4', 0, 1, 0))
  145. def end_h4(self):
  146. self.formatter.end_paragraph(1)
  147. self.formatter.pop_font()
  148. def start_h5(self, attrs):
  149. self.formatter.end_paragraph(1)
  150. self.formatter.push_font(('h5', 0, 1, 0))
  151. def end_h5(self):
  152. self.formatter.end_paragraph(1)
  153. self.formatter.pop_font()
  154. def start_h6(self, attrs):
  155. self.formatter.end_paragraph(1)
  156. self.formatter.push_font(('h6', 0, 1, 0))
  157. def end_h6(self):
  158. self.formatter.end_paragraph(1)
  159. self.formatter.pop_font()
  160. # --- Block Structuring Elements
  161. def do_p(self, attrs):
  162. self.formatter.end_paragraph(1)
  163. def start_pre(self, attrs):
  164. self.formatter.end_paragraph(1)
  165. self.formatter.push_font((AS_IS, AS_IS, AS_IS, 1))
  166. self.nofill = self.nofill + 1
  167. def end_pre(self):
  168. self.formatter.end_paragraph(1)
  169. self.formatter.pop_font()
  170. self.nofill = max(0, self.nofill - 1)
  171. def start_xmp(self, attrs):
  172. self.start_pre(attrs)
  173. self.setliteral('xmp') # Tell SGML parser
  174. def end_xmp(self):
  175. self.end_pre()
  176. def start_listing(self, attrs):
  177. self.start_pre(attrs)
  178. self.setliteral('listing') # Tell SGML parser
  179. def end_listing(self):
  180. self.end_pre()
  181. def start_address(self, attrs):
  182. self.formatter.end_paragraph(0)
  183. self.formatter.push_font((AS_IS, 1, AS_IS, AS_IS))
  184. def end_address(self):
  185. self.formatter.end_paragraph(0)
  186. self.formatter.pop_font()
  187. def start_blockquote(self, attrs):
  188. self.formatter.end_paragraph(1)
  189. self.formatter.push_margin('blockquote')
  190. def end_blockquote(self):
  191. self.formatter.end_paragraph(1)
  192. self.formatter.pop_margin()
  193. # --- List Elements
  194. def start_ul(self, attrs):
  195. self.formatter.end_paragraph(not self.list_stack)
  196. self.formatter.push_margin('ul')
  197. self.list_stack.append(['ul', '*', 0])
  198. def end_ul(self):
  199. if self.list_stack: del self.list_stack[-1]
  200. self.formatter.end_paragraph(not self.list_stack)
  201. self.formatter.pop_margin()
  202. def do_li(self, attrs):
  203. self.formatter.end_paragraph(0)
  204. if self.list_stack:
  205. [dummy, label, counter] = top = self.list_stack[-1]
  206. top[2] = counter = counter+1
  207. else:
  208. label, counter = '*', 0
  209. self.formatter.add_label_data(label, counter)
  210. def start_ol(self, attrs):
  211. self.formatter.end_paragraph(not self.list_stack)
  212. self.formatter.push_margin('ol')
  213. label = '1.'
  214. for a, v in attrs:
  215. if a == 'type':
  216. if len(v) == 1: v = v + '.'
  217. label = v
  218. self.list_stack.append(['ol', label, 0])
  219. def end_ol(self):
  220. if self.list_stack: del self.list_stack[-1]
  221. self.formatter.end_paragraph(not self.list_stack)
  222. self.formatter.pop_margin()
  223. def start_menu(self, attrs):
  224. self.start_ul(attrs)
  225. def end_menu(self):
  226. self.end_ul()
  227. def start_dir(self, attrs):
  228. self.start_ul(attrs)
  229. def end_dir(self):
  230. self.end_ul()
  231. def start_dl(self, attrs):
  232. self.formatter.end_paragraph(1)
  233. self.list_stack.append(['dl', '', 0])
  234. def end_dl(self):
  235. self.ddpop(1)
  236. if self.list_stack: del self.list_stack[-1]
  237. def do_dt(self, attrs):
  238. self.ddpop()
  239. def do_dd(self, attrs):
  240. self.ddpop()
  241. self.formatter.push_margin('dd')
  242. self.list_stack.append(['dd', '', 0])
  243. def ddpop(self, bl=0):
  244. self.formatter.end_paragraph(bl)
  245. if self.list_stack:
  246. if self.list_stack[-1][0] == 'dd':
  247. del self.list_stack[-1]
  248. self.formatter.pop_margin()
  249. # --- Phrase Markup
  250. # Idiomatic Elements
  251. def start_cite(self, attrs): self.start_i(attrs)
  252. def end_cite(self): self.end_i()
  253. def start_code(self, attrs): self.start_tt(attrs)
  254. def end_code(self): self.end_tt()
  255. def start_em(self, attrs): self.start_i(attrs)
  256. def end_em(self): self.end_i()
  257. def start_kbd(self, attrs): self.start_tt(attrs)
  258. def end_kbd(self): self.end_tt()
  259. def start_samp(self, attrs): self.start_tt(attrs)
  260. def end_samp(self): self.end_tt()
  261. def start_strong(self, attrs): self.start_b(attrs)
  262. def end_strong(self): self.end_b()
  263. def start_var(self, attrs): self.start_i(attrs)
  264. def end_var(self): self.end_i()
  265. # Typographic Elements
  266. def start_i(self, attrs):
  267. self.formatter.push_font((AS_IS, 1, AS_IS, AS_IS))
  268. def end_i(self):
  269. self.formatter.pop_font()
  270. def start_b(self, attrs):
  271. self.formatter.push_font((AS_IS, AS_IS, 1, AS_IS))
  272. def end_b(self):
  273. self.formatter.pop_font()
  274. def start_tt(self, attrs):
  275. self.formatter.push_font((AS_IS, AS_IS, AS_IS, 1))
  276. def end_tt(self):
  277. self.formatter.pop_font()
  278. def start_a(self, attrs):
  279. href = ''
  280. name = ''
  281. type = ''
  282. for attrname, value in attrs:
  283. value = value.strip()
  284. if attrname == 'href':
  285. href = value
  286. if attrname == 'name':
  287. name = value
  288. if attrname == 'type':
  289. type = value.lower()
  290. self.anchor_bgn(href, name, type)
  291. def end_a(self):
  292. self.anchor_end()
  293. # --- Line Break
  294. def do_br(self, attrs):
  295. self.formatter.add_line_break()
  296. # --- Horizontal Rule
  297. def do_hr(self, attrs):
  298. self.formatter.add_hor_rule()
  299. # --- Image
  300. def do_img(self, attrs):
  301. align = ''
  302. alt = '(image)'
  303. ismap = ''
  304. src = ''
  305. width = 0
  306. height = 0
  307. for attrname, value in attrs:
  308. if attrname == 'align':
  309. align = value
  310. if attrname == 'alt':
  311. alt = value
  312. if attrname == 'ismap':
  313. ismap = value
  314. if attrname == 'src':
  315. src = value
  316. if attrname == 'width':
  317. try: width = int(value)
  318. except ValueError: pass
  319. if attrname == 'height':
  320. try: height = int(value)
  321. except ValueError: pass
  322. self.handle_image(src, alt, ismap, align, width, height)
  323. # --- Really Old Unofficial Deprecated Stuff
  324. def do_plaintext(self, attrs):
  325. self.start_pre(attrs)
  326. self.setnomoretags() # Tell SGML parser
  327. # --- Unhandled tags
  328. def unknown_starttag(self, tag, attrs):
  329. pass
  330. def unknown_endtag(self, tag):
  331. pass
  332. def test(args = None):
  333. import sys, formatter
  334. if not args:
  335. args = sys.argv[1:]
  336. silent = args and args[0] == '-s'
  337. if silent:
  338. del args[0]
  339. if args:
  340. file = args[0]
  341. else:
  342. file = 'test.html'
  343. if file == '-':
  344. f = sys.stdin
  345. else:
  346. try:
  347. f = open(file, 'r')
  348. except IOError, msg:
  349. print file, ":", msg
  350. sys.exit(1)
  351. data = f.read()
  352. if f is not sys.stdin:
  353. f.close()
  354. if silent:
  355. f = formatter.NullFormatter()
  356. else:
  357. f = formatter.AbstractFormatter(formatter.DumbWriter())
  358. p = HTMLParser(f)
  359. p.feed(data)
  360. p.close()
  361. if __name__ == '__main__':
  362. test()