- Saved searches
- Use saved searches to filter your results more quickly
- License
- marmelo/python-htmlparser
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- html.parser — Simple HTML and XHTML parser¶
- Example HTML Parser Application¶
- Parse me!
- HTMLParser Methods¶
- Examples¶
- Python
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Python 3.x HTMLParser extension with ElementTree support.
License
marmelo/python-htmlparser
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Python 3.x HTMLParser extension with ElementTree support.
Why another Python HTML Parser?
There is no HTML Parser in the Python Standard Library. Actually, there is the html.parser.HTMLParser that simply traverses the DOM tree and allows us to be notified as each tag is being parsed.
Usually, when we parse HTML we want to query its elements and extract data from it. The most simple way to do this is to use XPath expressions. Python do support a simple (read limited) XPath engine into its ElementTree, but there is no way to parse an HTML document into XHTML and then use this library to query it.
This HTML Parser extends html.parser.HTMLParser returning an xml.etree.Element instance (the root element) which natively supports the ElementTree API.
You may use this code however you like. You may even copy-paste it into your project in order to keep the result clean and simple (a comment to this source is welcome!).
As the filename implies, this is a very naive approach to this problem. If you really need (or may use) a fully-fledged parsing library, lxml and BeautifulSoup are arguably the most used.
html = """ GitHub GitHub Project """ parser = NaiveHTMLParser() root = parser.feed(html) parser.close() # root is an xml.etree.Element and supports the ElementTree API # (e.g. you may use its limited support for XPath expressions) # get title print(root.find('head/title').text) # get all anchors for a in root.findall('.//a'): print(a.get('href')) # for more information, see: # http://docs.python.org/2/library/xml.etree.elementtree.html # http://docs.python.org/2/library/xml.etree.elementtree.html#xpath-support
GitHub https://github.com/marmelo https://github.com/marmelo/python-htmlparser
About
Python 3.x HTMLParser extension with ElementTree support.
html.parser — Simple HTML and XHTML parser¶
This module defines a class HTMLParser which serves as the basis for parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.
class html.parser. HTMLParser ( * , convert_charrefs = True ) ¶
Create a parser instance able to parse invalid markup.
If convert_charrefs is True (the default), all character references (except the ones in script / style elements) are automatically converted to the corresponding Unicode characters.
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.
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.
Changed in version 3.4: convert_charrefs keyword argument added.
Changed in version 3.5: The default value for argument convert_charrefs is now True .
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:
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('' 'Parse me!
')
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
HTMLParser Methods¶
HTMLParser instances have the following methods:
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 close() is called. data must be str .
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 HTMLParser base class method close() .
Reset the instance. Loses all unprocessed data. This is called implicitly at instantiation time.
Return current line number and offset.
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.).
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 handle_startendtag() ):
HTMLParser. handle_starttag ( tag , attrs ) ¶
This method is called to handle the start tag of an element (e.g. ).
The tag argument is the name of the tag converted to lower case. The attrs argument is a list of (name, value) pairs containing the attributes found inside the tag’s <> brackets. The name will be translated to lower case, and quotes in the value have been removed, and character and entity references have been replaced.
For instance, for the tag , this method would be called as handle_starttag(‘a’, [(‘href’, ‘https://www.cwi.nl/’)]) .
All entity references from html.entities are replaced in the attribute values.
HTMLParser. handle_endtag ( tag ) ¶
This method is called to handle the end tag of an element (e.g.