1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
|
<span id="html-parser-simple-html-and-xhtml-parser"></span><h1>html.parser — Simple HTML and XHTML parser</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/html/parser.py">Lib/html/parser.py</a></p> <p>This module defines a class <a class="reference internal" href="#html.parser.HTMLParser" title="html.parser.HTMLParser"><code>HTMLParser</code></a> which serves as the basis for parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.</p> <dl class="py class"> <dt class="sig sig-object py" id="html.parser.HTMLParser">
<code>class html.parser.HTMLParser(*, convert_charrefs=True)</code> </dt> <dd>
<p>Create a parser instance able to parse invalid markup.</p> <p>If <em>convert_charrefs</em> is <code>True</code> (the default), all character references (except the ones in <code>script</code>/<code>style</code> elements) are automatically converted to the corresponding Unicode characters.</p> <p>An <a class="reference internal" href="#html.parser.HTMLParser" title="html.parser.HTMLParser"><code>HTMLParser</code></a> instance is fed HTML data and calls handler methods when start tags, end tags, text, comments, and other markup elements are encountered. The user should subclass <a class="reference internal" href="#html.parser.HTMLParser" title="html.parser.HTMLParser"><code>HTMLParser</code></a> and override its methods to implement the desired behavior.</p> <p>This parser does not check that end tags match start tags or call the end-tag handler for elements which are closed implicitly by closing an outer element.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span><em>convert_charrefs</em> keyword argument added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The default value for argument <em>convert_charrefs</em> is now <code>True</code>.</p> </div> </dd>
</dl> <section id="example-html-parser-application"> <h2>Example HTML Parser Application</h2> <p>As a basic example, below is a simple HTML parser that uses the <a class="reference internal" href="#html.parser.HTMLParser" title="html.parser.HTMLParser"><code>HTMLParser</code></a> class to print out start tags, end tags, and data as they are encountered:</p> <pre data-language="python">from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print("Encountered a start tag:", tag)
def handle_endtag(self, tag):
print("Encountered an end tag :", tag)
def handle_data(self, data):
print("Encountered some data :", data)
parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
'<body><h1>Parse me!</h1></body></html>')
</pre> <p>The output will then be:</p> <pre data-language="none">Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h1
Encountered some data : Parse me!
Encountered an end tag : h1
Encountered an end tag : body
Encountered an end tag : html
</pre> </section> <section id="htmlparser-methods"> <h2>HTMLParser Methods</h2> <p><a class="reference internal" href="#html.parser.HTMLParser" title="html.parser.HTMLParser"><code>HTMLParser</code></a> instances have the following methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="html.parser.HTMLParser.feed">
<code>HTMLParser.feed(data)</code> </dt> <dd>
<p>Feed some text to the parser. It is processed insofar as it consists of complete elements; incomplete data is buffered until more data is fed or <a class="reference internal" href="#html.parser.HTMLParser.close" title="html.parser.HTMLParser.close"><code>close()</code></a> is called. <em>data</em> must be <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="html.parser.HTMLParser.close">
<code>HTMLParser.close()</code> </dt> <dd>
<p>Force processing of all buffered data as if it were followed by an end-of-file mark. This method may be redefined by a derived class to define additional processing at the end of the input, but the redefined version should always call the <a class="reference internal" href="#html.parser.HTMLParser" title="html.parser.HTMLParser"><code>HTMLParser</code></a> base class method <a class="reference internal" href="#html.parser.HTMLParser.close" title="html.parser.HTMLParser.close"><code>close()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="html.parser.HTMLParser.reset">
<code>HTMLParser.reset()</code> </dt> <dd>
<p>Reset the instance. Loses all unprocessed data. This is called implicitly at instantiation time.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="html.parser.HTMLParser.getpos">
<code>HTMLParser.getpos()</code> </dt> <dd>
<p>Return current line number and offset.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="html.parser.HTMLParser.get_starttag_text">
<code>HTMLParser.get_starttag_text()</code> </dt> <dd>
<p>Return the text of the most recently opened start tag. This should not normally be needed for structured processing, but may be useful in dealing with HTML “as deployed” or for re-generating input with minimal changes (whitespace between attributes can be preserved, etc.).</p> </dd>
</dl> <p>The following methods are called when data or markup elements are encountered and they are meant to be overridden in a subclass. The base class implementations do nothing (except for <a class="reference internal" href="#html.parser.HTMLParser.handle_startendtag" title="html.parser.HTMLParser.handle_startendtag"><code>handle_startendtag()</code></a>):</p> <dl class="py method"> <dt class="sig sig-object py" id="html.parser.HTMLParser.handle_starttag">
<code>HTMLParser.handle_starttag(tag, attrs)</code> </dt> <dd>
<p>This method is called to handle the start tag of an element (e.g. <code><div id="main"></code>).</p> <p>The <em>tag</em> argument is the name of the tag converted to lower case. The <em>attrs</em> argument is a list of <code>(name, value)</code> pairs containing the attributes found inside the tag’s <code><></code> brackets. The <em>name</em> will be translated to lower case, and quotes in the <em>value</em> have been removed, and character and entity references have been replaced.</p> <p>For instance, for the tag <code><A HREF="https://www.cwi.nl/"></code>, this method would be called as <code>handle_starttag('a', [('href', 'https://www.cwi.nl/')])</code>.</p> <p>All entity references from <a class="reference internal" href="html.entities#module-html.entities" title="html.entities: Definitions of HTML general entities."><code>html.entities</code></a> are replaced in the attribute values.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="html.parser.HTMLParser.handle_endtag">
<code>HTMLParser.handle_endtag(tag)</code> </dt> <dd>
<p>This method is called to handle the end tag of an element (e.g. <code></div></code>).</p> <p>The <em>tag</em> argument is the name of the tag converted to lower case.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="html.parser.HTMLParser.handle_startendtag">
<code>HTMLParser.handle_startendtag(tag, attrs)</code> </dt> <dd>
<p>Similar to <a class="reference internal" href="#html.parser.HTMLParser.handle_starttag" title="html.parser.HTMLParser.handle_starttag"><code>handle_starttag()</code></a>, but called when the parser encounters an XHTML-style empty tag (<code><img ... /></code>). This method may be overridden by subclasses which require this particular lexical information; the default implementation simply calls <a class="reference internal" href="#html.parser.HTMLParser.handle_starttag" title="html.parser.HTMLParser.handle_starttag"><code>handle_starttag()</code></a> and <a class="reference internal" href="#html.parser.HTMLParser.handle_endtag" title="html.parser.HTMLParser.handle_endtag"><code>handle_endtag()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="html.parser.HTMLParser.handle_data">
<code>HTMLParser.handle_data(data)</code> </dt> <dd>
<p>This method is called to process arbitrary data (e.g. text nodes and the content of <code><script>...</script></code> and <code><style>...</style></code>).</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="html.parser.HTMLParser.handle_entityref">
<code>HTMLParser.handle_entityref(name)</code> </dt> <dd>
<p>This method is called to process a named character reference of the form <code>&name;</code> (e.g. <code>&gt;</code>), where <em>name</em> is a general entity reference (e.g. <code>'gt'</code>). This method is never called if <em>convert_charrefs</em> is <code>True</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="html.parser.HTMLParser.handle_charref">
<code>HTMLParser.handle_charref(name)</code> </dt> <dd>
<p>This method is called to process decimal and hexadecimal numeric character references of the form <code>&#<em>NNN</em>;</code> and <code>&#x<em>NNN</em>;</code>. For example, the decimal equivalent for <code>&gt;</code> is <code>&#62;</code>, whereas the hexadecimal is <code>&#x3E;</code>; in this case the method will receive <code>'62'</code> or <code>'x3E'</code>. This method is never called if <em>convert_charrefs</em> is <code>True</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="html.parser.HTMLParser.handle_comment">
<code>HTMLParser.handle_comment(data)</code> </dt> <dd>
<p>This method is called when a comment is encountered (e.g. <code><!--comment--></code>).</p> <p>For example, the comment <code><!-- comment --></code> will cause this method to be called with the argument <code>' comment '</code>.</p> <p>The content of Internet Explorer conditional comments (condcoms) will also be sent to this method, so, for <code><!--[if IE 9]>IE9-specific content<![endif]--></code>, this method will receive <code>'[if IE 9]>IE9-specific content<![endif]'</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="html.parser.HTMLParser.handle_decl">
<code>HTMLParser.handle_decl(decl)</code> </dt> <dd>
<p>This method is called to handle an HTML doctype declaration (e.g. <code><!DOCTYPE html></code>).</p> <p>The <em>decl</em> parameter will be the entire contents of the declaration inside the <code><!...></code> markup (e.g. <code>'DOCTYPE html'</code>).</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="html.parser.HTMLParser.handle_pi">
<code>HTMLParser.handle_pi(data)</code> </dt> <dd>
<p>Method called when a processing instruction is encountered. The <em>data</em> parameter will contain the entire processing instruction. For example, for the processing instruction <code><?proc color='red'></code>, this method would be called as <code>handle_pi("proc color='red'")</code>. It is intended to be overridden by a derived class; the base class implementation does nothing.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <a class="reference internal" href="#html.parser.HTMLParser" title="html.parser.HTMLParser"><code>HTMLParser</code></a> class uses the SGML syntactic rules for processing instructions. An XHTML processing instruction using the trailing <code>'?'</code> will cause the <code>'?'</code> to be included in <em>data</em>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="html.parser.HTMLParser.unknown_decl">
<code>HTMLParser.unknown_decl(data)</code> </dt> <dd>
<p>This method is called when an unrecognized declaration is read by the parser.</p> <p>The <em>data</em> parameter will be the entire contents of the declaration inside the <code><![...]></code> markup. It is sometimes useful to be overridden by a derived class. The base class implementation does nothing.</p> </dd>
</dl> </section> <section id="examples"> <span id="htmlparser-examples"></span><h2>Examples</h2> <p>The following class implements a parser that will be used to illustrate more examples:</p> <pre data-language="python">from html.parser import HTMLParser
from html.entities import name2codepoint
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print("Start tag:", tag)
for attr in attrs:
print(" attr:", attr)
def handle_endtag(self, tag):
print("End tag :", tag)
def handle_data(self, data):
print("Data :", data)
def handle_comment(self, data):
print("Comment :", data)
def handle_entityref(self, name):
c = chr(name2codepoint[name])
print("Named ent:", c)
def handle_charref(self, name):
if name.startswith('x'):
c = chr(int(name[1:], 16))
else:
c = chr(int(name))
print("Num ent :", c)
def handle_decl(self, data):
print("Decl :", data)
parser = MyHTMLParser()
</pre> <p>Parsing a doctype:</p> <pre data-language="python">>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
... '"http://www.w3.org/TR/html4/strict.dtd">')
Decl : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
</pre> <p>Parsing an element with a few attributes and a title:</p> <pre data-language="python">>>> parser.feed('<img src="python-logo.png" alt="The Python logo">')
Start tag: img
attr: ('src', 'python-logo.png')
attr: ('alt', 'The Python logo')
>>>
>>> parser.feed('<h1>Python</h1>')
Start tag: h1
Data : Python
End tag : h1
</pre> <p>The content of <code>script</code> and <code>style</code> elements is returned as is, without further parsing:</p> <pre data-language="python">>>> parser.feed('<style type="text/css">#python { color: green }</style>')
Start tag: style
attr: ('type', 'text/css')
Data : #python { color: green }
End tag : style
>>> parser.feed('<script type="text/javascript">'
... 'alert("<strong>hello!</strong>");</script>')
Start tag: script
attr: ('type', 'text/javascript')
Data : alert("<strong>hello!</strong>");
End tag : script
</pre> <p>Parsing comments:</p> <pre data-language="python">>>> parser.feed('<!-- a comment -->'
... '<!--[if IE 9]>IE-specific content<![endif]-->')
Comment : a comment
Comment : [if IE 9]>IE-specific content<![endif]
</pre> <p>Parsing named and numeric character references and converting them to the correct char (note: these 3 references are all equivalent to <code>'>'</code>):</p> <pre data-language="python">>>> parser.feed('&gt;&#62;&#x3E;')
Named ent: >
Num ent : >
Num ent : >
</pre> <p>Feeding incomplete chunks to <a class="reference internal" href="#html.parser.HTMLParser.feed" title="html.parser.HTMLParser.feed"><code>feed()</code></a> works, but <a class="reference internal" href="#html.parser.HTMLParser.handle_data" title="html.parser.HTMLParser.handle_data"><code>handle_data()</code></a> might be called more than once (unless <em>convert_charrefs</em> is set to <code>True</code>):</p> <pre data-language="python">>>> for chunk in ['<sp', 'an>buff', 'ered ', 'text</s', 'pan>']:
... parser.feed(chunk)
...
Start tag: span
Data : buff
Data : ered
Data : text
End tag : span
</pre> <p>Parsing invalid HTML (e.g. unquoted attributes) also works:</p> <pre data-language="python">>>> parser.feed('<p><a class=link href=#main>tag soup</p ></a>')
Start tag: p
Start tag: a
attr: ('class', 'link')
attr: ('href', '#main')
Data : tag soup
End tag : p
End tag : a
</pre> </section> <div class="_attribution">
<p class="_attribution-p">
© 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br>
<a href="https://docs.python.org/3.12/library/html.parser.html" class="_attribution-link">https://docs.python.org/3.12/library/html.parser.html</a>
</p>
</div>
|