summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fhtml.parser.html
diff options
context:
space:
mode:
Diffstat (limited to 'devdocs/python~3.12/library%2Fhtml.parser.html')
-rw-r--r--devdocs/python~3.12/library%2Fhtml.parser.html162
1 files changed, 162 insertions, 0 deletions
diff --git a/devdocs/python~3.12/library%2Fhtml.parser.html b/devdocs/python~3.12/library%2Fhtml.parser.html
new file mode 100644
index 00000000..de2bf34a
--- /dev/null
+++ b/devdocs/python~3.12/library%2Fhtml.parser.html
@@ -0,0 +1,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('&lt;html&gt;&lt;head&gt;&lt;title&gt;Test&lt;/title&gt;&lt;/head&gt;'
+ '&lt;body&gt;&lt;h1&gt;Parse me!&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;')
+</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>&lt;div id="main"&gt;</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>&lt;&gt;</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>&lt;A HREF="https://www.cwi.nl/"&gt;</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>&lt;/div&gt;</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>&lt;img ... /&gt;</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>&lt;script&gt;...&lt;/script&gt;</code> and <code>&lt;style&gt;...&lt;/style&gt;</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>&amp;name;</code> (e.g. <code>&amp;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>&amp;#<em>NNN</em>;</code> and <code>&amp;#x<em>NNN</em>;</code>. For example, the decimal equivalent for <code>&amp;gt;</code> is <code>&amp;#62;</code>, whereas the hexadecimal is <code>&amp;#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>&lt;!--comment--&gt;</code>).</p> <p>For example, the comment <code>&lt;!-- comment --&gt;</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>&lt;!--[if IE 9]&gt;IE9-specific content&lt;![endif]--&gt;</code>, this method will receive <code>'[if IE 9]&gt;IE9-specific content&lt;![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>&lt;!DOCTYPE html&gt;</code>).</p> <p>The <em>decl</em> parameter will be the entire contents of the declaration inside the <code>&lt;!...&gt;</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>&lt;?proc color='red'&gt;</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>&lt;![...]&gt;</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">&gt;&gt;&gt; parser.feed('&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
+... '"http://www.w3.org/TR/html4/strict.dtd"&gt;')
+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">&gt;&gt;&gt; parser.feed('&lt;img src="python-logo.png" alt="The Python logo"&gt;')
+Start tag: img
+ attr: ('src', 'python-logo.png')
+ attr: ('alt', 'The Python logo')
+&gt;&gt;&gt;
+&gt;&gt;&gt; parser.feed('&lt;h1&gt;Python&lt;/h1&gt;')
+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">&gt;&gt;&gt; parser.feed('&lt;style type="text/css"&gt;#python { color: green }&lt;/style&gt;')
+Start tag: style
+ attr: ('type', 'text/css')
+Data : #python { color: green }
+End tag : style
+
+&gt;&gt;&gt; parser.feed('&lt;script type="text/javascript"&gt;'
+... 'alert("&lt;strong&gt;hello!&lt;/strong&gt;");&lt;/script&gt;')
+Start tag: script
+ attr: ('type', 'text/javascript')
+Data : alert("&lt;strong&gt;hello!&lt;/strong&gt;");
+End tag : script
+</pre> <p>Parsing comments:</p> <pre data-language="python">&gt;&gt;&gt; parser.feed('&lt;!-- a comment --&gt;'
+... '&lt;!--[if IE 9]&gt;IE-specific content&lt;![endif]--&gt;')
+Comment : a comment
+Comment : [if IE 9]&gt;IE-specific content&lt;![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>'&gt;'</code>):</p> <pre data-language="python">&gt;&gt;&gt; parser.feed('&amp;gt;&amp;#62;&amp;#x3E;')
+Named ent: &gt;
+Num ent : &gt;
+Num ent : &gt;
+</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">&gt;&gt;&gt; for chunk in ['&lt;sp', 'an&gt;buff', 'ered ', 'text&lt;/s', 'pan&gt;']:
+... 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">&gt;&gt;&gt; parser.feed('&lt;p&gt;&lt;a class=link href=#main&gt;tag soup&lt;/p &gt;&lt;/a&gt;')
+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">
+ &copy; 2001&ndash;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>