Python中使用HTMLParser解析html实例
前几天遇到一个问题,需要把网页中的一部分内容挑出来,于是找到了urllib和HTMLParser两个库.urllib可以将网页爬下来,然后交由HTMLParser解析,初次使用这个库,在查官方文档时也遇到了一些问题,在这里写下来与大家分享.
一个例子
from HTMLParser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print "a start tag:",tag,self.getpos()
parser=MyHTMLParser()
parser.feed('
"hello"
这个例子里HTMLParser是基类,重载了他的handle_starttag方法,输出了一些信息.parser是MyHTMLParser的实例,调用feed方法开始解析函数.值得注意的是,不需要显示调用handle_starttag方法就会执行.
HTMLParser方法的调用方式困惑了我很长时间,看了很多博文才恍然大悟,HTMLParser含有的方法分为两类,一类是需要显式调用的,而另一类不需显示调用.
不需显式调用的方法
下面的这些函数在解析的过程中会触发,但是默认情况下不会产生任何副作用,因而我们要根据自己的需求重载.
1.HTMLParser.handle_starttag(tag,attrs): 解析时遇到开始标签调用,如
,参数tag是标签名,这里是'p',attrs为标签所有属性(name,value)列表,这里是[('class','para')]
2.HTMLParser.handle_endtag(tag): 遇到结束标签时调用,tag是标签名
3.HTMLPars.handle_data(data): 遇到标签中间的内容时调用,如,参数data为开闭标签间的内容.值得注意的是在形如
...
当然还有其他函数,这里不做介绍
显式调用的方法
1.HTMLParser.feed(data): 参数为需要解析的html字符串,调用后字符串开始被解析
2.HTMLParser.getpos(): 返回当前的行号和偏移位置,如(23,5)
3.HTMLParser.get_starttag_text(): 返回当前位置最近的开始标签的内容
所有的内容写完了,最后还有一点注意事项,HTMLParser只是一个简单的模块,解析html的功能并不完善,例如不能准确的分别开标签和"自闭标签",看下面代码:
from HTMLParser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self,tag,attrs):
print 'begin tag',tag
def handle_startendtag(self,tag,attrs):
print 'begin end tag',tag
str1='
'
str2='
'
parser=MyHTMLParser()
parser.feed(str1) # 输出 "begin tag br"
parser.feed(str2) # 输出 "begin end br"

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
