2017年7月14日 星期五

[Python Std Library] 19.1. HTMLParser — Simple HTML and XHTML parser

Source From Here 
Preface 
This module defines a class HTMLParser which serves as the basis for parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML. Unlike the parser in htmllib, this parser is not based on the SGML parser in sgmllib. 
Notes. 
The HTMLParser module has been renamed to html.parser in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

- class HTMLParser.HTMLParser 
An HTMLParser 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 HTMLParser and override its methods to implement the desired behavior. 

The HTMLParserHTMLParser class is instantiated without arguments. 

Unlike the parser in htmllib, 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.

An exception is defined as well: 
- exception HTMLParser.HTMLParseError 
HTMLParser is able to handle broken markup, but in some cases it might raise this exception when it encounters an error while parsing. This exception provides three attributes: msg is a brief message explaining the error, lineno is the number of the line on which the broken construct was detected, and offset is the number of characters into the line at which the construct starts.

Example HTML Parser Application 
As a basic example, below is a simple HTML parser that uses the HTMLParser class to print out start tags, end tags and data as they are encountered: 
  1. from HTMLParser import HTMLParser  
  2.   
  3. # create a subclass and override the handler methods  
  4. class MyHTMLParser(HTMLParser):  
  5.     def handle_starttag(self, tag, attrs):  
  6.         print "Encountered a start tag:", tag  
  7.   
  8.     def handle_endtag(self, tag):  
  9.         print "Encountered an end tag :", tag  
  10.   
  11.     def handle_data(self, data):  
  12.         print "Encountered some data  :", data  
  13.   
  14. # instantiate the parser and fed it some HTML  
  15. parser = MyHTMLParser()  
  16. parser.feed('Test'  
  17.             '

    Parse me!

')  The output will then be: 
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


沒有留言:

張貼留言

[ Python 文章收集 ] SQLAlchemy quick start with PostgreSQL

Source From   Here   Preface   This is a quick tutorial for getting started with   SQLAlchemy Core API .   Prerequisites   In this quick st...