This recommended combination is Xml.dom.minidom and XPath. Where Xml.dom.minidom is the standard library for Python, no installation is required. XPath is an open source project Py-dom-xpath by Google.
Install Py-dom-xpath:
- Download the compressed package from https://py-dom-xpath.googlecode.com/files/py-dom-xpath-0.1.tar.gz, unzip it.
- CD to py-dom-xpath-0.1 directory
- Execute command: C:\python27\python setup.py install
- After the command executes, this directory has two more folders, build and dist, and copies the XPath directory under the/build/lib/folder to the C:\Python27\Lib directory, which is the installation complete.
The test HTML file, simple.html, reads as follows:
1 <!DOCTYPE HTML>2 <HTML>3 <Head>4 <title>A simple HTML file</title>5 <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"/>6 </Head>7 <Body>8 <Div>9 <Div>A</Div>Ten <Div>B</Div> One <Div>C</Div> A </Div> - </Body> - </HTML>
Python file:
1 import XPath 2 import Xml.dom.minidom 3 4 xml = Xml.dom.minidom.parse ( '
A notable problem is that the first line of simple.html, the document header <! The ' DOCTYPE ' in DOCTYPE html> must be capitalized, otherwise xml.dom.minidom parsing will fail. In the next article, we'll cover another library that parses HTML, and there's no such problem.
Parsing HTML with XPath and xml.dom in Python