1 """A parser for HTML and XHTML."""
3 # This file is based on sgmllib.py, but the API is slightly different.
5 # XXX There should be a way to distinguish between PCDATA (parsed
6 # character data -- the normal case), RCDATA (replaceable character
7 # data -- only char and entity references and end tags are special)
8 # and CDATA (character data -- only end tags are special).
15 # Regular expressions used for parsing
17 interesting_normal
= re
.compile('[&<]')
18 interesting_cdata
= re
.compile(r
'<(/|\Z)')
19 incomplete
= re
.compile('&[a-zA-Z#]')
21 entityref
= re
.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')
22 charref
= re
.compile('&#(?:[0-9]+|[xX][0-9a-fA-F]+)[^0-9a-fA-F]')
24 starttagopen
= re
.compile('<[a-zA-Z]')
25 piclose
= re
.compile('>')
26 endtagopen
= re
.compile('</')
27 commentclose
= re
.compile(r
'--\s*>')
28 tagfind
= re
.compile('[a-zA-Z][-.a-zA-Z0-9:_]*')
29 attrfind
= re
.compile(
30 r
'\s*([a-zA-Z_][-.:a-zA-Z_0-9]*)(\s*=\s*'
31 r
'(\'[^
\']*\'|
"[^"]*"|[-a-zA-Z0-9./:;+*%?!&$\(\)_#=~]*))?')
33 locatestarttagend = re.compile(r"""
34 <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name
35 (?:\s+ # whitespace before attribute name
36 (?:[a-zA-Z_][-.:a-zA-Z0-9_]* # attribute name
37 (?:\s*=\s* # value indicator
38 (?:'[^']*' # LITA-enclosed value
39 |\"[^\"]*\" # LIT-enclosed value
40 |[^'\">\s]+ # bare value
45 \s* # trailing whitespace
47 endendtag = re.compile('>')
48 endtagfind = re.compile('</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
51 class HTMLParseError(Exception):
52 """Exception raised for all parse errors."""
54 def __init__(self, msg, position=(None, None)):
57 self.lineno = position[0]
58 self.offset = position[1]
62 if self.lineno is not None:
63 result = result + ", at line
%d" % self.lineno
64 if self.offset is not None:
65 result = result + ", column
%d" % (self.offset + 1)
69 class HTMLParser(markupbase.ParserBase):
70 """Find tags and other markup and call handler functions.
78 Start tags are handled by calling self.handle_starttag() or
79 self.handle_startendtag(); end tags by self.handle_endtag(). The
80 data between tags is passed from the parser to the derived class
81 by calling self.handle_data() with the data as argument (the data
82 may be split up in arbitrary chunks). Entity references are
83 passed by calling self.handle_entityref() with the entity
84 reference as the argument. Numeric character references are
85 passed to self.handle_charref() with the string containing the
86 reference as the argument.
89 CDATA_CONTENT_ELEMENTS = ("script
", "style
")
93 """Initialize and reset this instance."""
97 """Reset this instance. Loses all unprocessed data."""
101 self.interesting = interesting_normal
102 markupbase.ParserBase.reset(self)
104 def feed(self, data):
105 """Feed data to the parser.
107 Call this as often as you want, with as little or as much text
108 as you want (may include '\n').
110 self.rawdata = self.rawdata + data
114 """Handle any buffered data."""
117 def error(self, message):
118 raise HTMLParseError(message, self.getpos())
120 __starttag_text = None
122 def get_starttag_text(self):
123 """Return full source of start tag: '<...>'."""
124 return self.__starttag_text
126 def set_cdata_mode(self):
127 self.interesting = interesting_cdata
129 def clear_cdata_mode(self):
130 self.interesting = interesting_normal
132 # Internal -- handle data as far as reasonable. May leave state
133 # and data to be processed by a subsequent call. If 'end' is
134 # true, force handling all data as if followed by EOF marker.
135 def goahead(self, end):
136 rawdata = self.rawdata
140 match = self.interesting.search(rawdata, i) # < or &
145 if i < j: self.handle_data(rawdata[i:j])
146 i = self.updatepos(i, j)
148 if rawdata[i] == '<':
149 if starttagopen.match(rawdata, i): # < + letter
150 k = self.parse_starttag(i)
151 elif endtagopen.match(rawdata, i): # </
152 k = self.parse_endtag(i)
154 self.clear_cdata_mode()
155 elif rawdata.startswith("<!--", i): # <!--
156 k = self.parse_comment(i)
157 elif rawdata.startswith("<?
", i): # <?
159 elif rawdata.startswith("<!", i): # <!
160 k = self.parse_declaration(i)
162 self.handle_data("<")
168 self.error("EOF
in middle of construct
")
170 i = self.updatepos(i, k)
171 elif rawdata[i:i+2] == "&#":
172 match
= charref
.match(rawdata
, i
)
174 name
= match
.group()[2:-1]
175 self
.handle_charref(name
)
177 if rawdata
[k
-1] != ';':
179 i
= self
.updatepos(i
, k
)
183 elif rawdata
[i
] == '&':
184 match
= entityref
.match(rawdata
, i
)
186 name
= match
.group(1)
187 self
.handle_entityref(name
)
189 if rawdata
[k
-1] != ';':
191 i
= self
.updatepos(i
, k
)
193 match
= incomplete
.match(rawdata
, i
)
195 # match.group() will contain at least 2 chars
197 if end
and match
.group() == rest
:
198 self
.error("EOF in middle of entity or char ref")
202 # not the end of the buffer, and can't be confused
203 # with some other construct
204 self
.handle_data("&")
205 i
= self
.updatepos(i
, i
+ 1)
209 assert 0, "interesting.search() lied"
212 self
.handle_data(rawdata
[i
:n
])
213 i
= self
.updatepos(i
, n
)
214 self
.rawdata
= rawdata
[i
:]
216 # Internal -- parse comment, return end or -1 if not terminated
217 def parse_comment(self
, i
, report
=1):
218 rawdata
= self
.rawdata
219 assert rawdata
[i
:i
+4] == '<!--', 'unexpected call to parse_comment()'
220 match
= commentclose
.search(rawdata
, i
+4)
225 self
.handle_comment(rawdata
[i
+4: j
])
229 # Internal -- parse processing instr, return end or -1 if not terminated
230 def parse_pi(self
, i
):
231 rawdata
= self
.rawdata
232 assert rawdata
[i
:i
+2] == '<?', 'unexpected call to parse_pi()'
233 match
= piclose
.search(rawdata
, i
+2) # >
237 self
.handle_pi(rawdata
[i
+2: j
])
241 # Internal -- handle starttag, return end or -1 if not terminated
242 def parse_starttag(self
, i
):
243 self
.__starttag
_text
= None
244 endpos
= self
.check_for_whole_start_tag(i
)
247 rawdata
= self
.rawdata
248 self
.__starttag
_text
= rawdata
[i
:endpos
]
250 # Now parse the data between i+1 and j into a tag and attrs
252 match
= tagfind
.match(rawdata
, i
+1)
253 assert match
, 'unexpected call to parse_starttag()'
255 self
.lasttag
= tag
= string
.lower(rawdata
[i
+1:k
])
258 m
= attrfind
.match(rawdata
, k
)
261 attrname
, rest
, attrvalue
= m
.group(1, 2, 3)
264 elif attrvalue
[:1] == '\'' == attrvalue
[-1:] or \
265 attrvalue
[:1] == '"' == attrvalue
[-1:]:
266 attrvalue
= attrvalue
[1:-1]
267 attrvalue
= self
.unescape(attrvalue
)
268 attrs
.append((string
.lower(attrname
), attrvalue
))
271 end
= string
.strip(rawdata
[k
:endpos
])
272 if end
not in (">", "/>"):
273 lineno
, offset
= self
.getpos()
274 if "\n" in self
.__starttag
_text
:
275 lineno
= lineno
+ string
.count(self
.__starttag
_text
, "\n")
276 offset
= len(self
.__starttag
_text
) \
277 - string
.rfind(self
.__starttag
_text
, "\n")
279 offset
= offset
+ len(self
.__starttag
_text
)
280 self
.error("junk characters in start tag: %s"
281 % `rawdata
[k
:endpos
][:20]`
)
283 # XHTML-style empty tag: <span attr="value" />
284 self
.handle_startendtag(tag
, attrs
)
286 self
.handle_starttag(tag
, attrs
)
287 if tag
in self
.CDATA_CONTENT_ELEMENTS
:
288 self
.set_cdata_mode()
291 # Internal -- check to see if we have a complete starttag; return end
292 # or -1 if incomplete.
293 def check_for_whole_start_tag(self
, i
):
294 rawdata
= self
.rawdata
295 m
= locatestarttagend
.match(rawdata
, i
)
298 next
= rawdata
[j
:j
+1]
309 self
.updatepos(i
, j
+ 1)
310 self
.error("malformed empty start tag")
314 if next
in ("abcdefghijklmnopqrstuvwxyz=/"
315 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
316 # end of input in or before attribute value, or we have the
317 # '/' from a '/>' ending
320 self
.error("malformed start tag")
321 raise AssertionError("we should not get here!")
323 # Internal -- parse endtag, return end or -1 if incomplete
324 def parse_endtag(self
, i
):
325 rawdata
= self
.rawdata
326 assert rawdata
[i
:i
+2] == "</", "unexpected call to parse_endtag"
327 match
= endendtag
.search(rawdata
, i
+1) # >
331 match
= endtagfind
.match(rawdata
, i
) # </ + tag + >
333 self
.error("bad end tag: %s" % `rawdata
[i
:j
]`
)
335 self
.handle_endtag(string
.lower(tag
))
338 # Overridable -- finish processing of start+end tag: <tag.../>
339 def handle_startendtag(self
, tag
, attrs
):
340 self
.handle_starttag(tag
, attrs
)
341 self
.handle_endtag(tag
)
343 # Overridable -- handle start tag
344 def handle_starttag(self
, tag
, attrs
):
347 # Overridable -- handle end tag
348 def handle_endtag(self
, tag
):
351 # Overridable -- handle character reference
352 def handle_charref(self
, name
):
355 # Overridable -- handle entity reference
356 def handle_entityref(self
, name
):
359 # Overridable -- handle data
360 def handle_data(self
, data
):
363 # Overridable -- handle comment
364 def handle_comment(self
, data
):
367 # Overridable -- handle declaration
368 def handle_decl(self
, decl
):
371 # Overridable -- handle processing instruction
372 def handle_pi(self
, data
):
375 def unknown_decl(self
, data
):
376 self
.error("unknown declaration: " + `data`
)
378 # Internal -- helper to remove special character quoting
379 def unescape(self
, s
):
382 s
= string
.replace(s
, "<", "<")
383 s
= string
.replace(s
, ">", ">")
384 s
= string
.replace(s
, "'", "'")
385 s
= string
.replace(s
, """, '"')
386 s
= string
.replace(s
, "&", "&") # Must be last