HTMLParser是python用來解析html的模塊。它能夠分析出html裏面的標籤、數據等等,是一種處理html的簡便途徑。HTMLParser採用的是一種事件驅動的模式,當HTMLParser找到一個特定的標記時,它會去調用一個用戶定義的函數,以此來通知程序處理。它主要的用戶回調函數的命名都是以handler_開頭的,都是HTMLParser的成員函數。當咱們使用時,就從HTMLParser派生出新的類,而後從新定義這幾個以handler_開頭的函數便可。這幾個函數包括:html
handle_startendtag 處理開始標籤和結束標籤
handle_starttag 處理開始標籤,好比<xx>
handle_endtag 處理結束標籤,好比</xx>
handle_charref 處理特殊字符串,就是以&#開頭的,通常是內碼錶示的字符
handle_entityref 處理一些特殊字符,以&開頭的,好比
handle_data 處理數據,就是<xx>data</xx>中間的那些數據
handle_comment 處理註釋
handle_decl 處理<!開頭的,好比<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
handle_pi 處理形如<?instruction>的東西python
下面是利用HTMLParser抓取豆瓣電影的程序json
# -*- coding: utf-8 -*- import urllib2 from HTMLParser import HTMLParser class MovieParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.movies = [] def handle_starttag(self, tag, attrs): def _attr(attrlist, attrname): for attr in attrlist: if attr[0] == attrname: return attr[1] return None if tag == 'li' and _attr(attrs, 'data-title') and _attr(attrs, 'data-category') == 'nowplaying': movie = {} movie['title'] = _attr(attrs, 'data-title') movie['score'] = _attr(attrs, 'data-score') movie['director'] = _attr(attrs, 'data-director') movie['actors'] = _attr(attrs, 'data-actors') self.movies.append(movie) print('%(title)s|%(score)s|%(director)s|%(actors)s' % movie) def nowplaying_movies(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36'} req = urllib2.Request(url, headers=headers) s = urllib2.urlopen(req) parser = MovieParser() parser.feed(s.read()) s.close() return parser.movies if __name__ == '__main__': url = 'http://movie.douban.com/nowplaying/xiamen/' movies = nowplaying_movies(url) import json print('%s' % json.dumps(movies, sort_keys=True, indent=4, separators=(',', ': ')))
上面抓取熱門電影的核心程序app
def handle_starttag(self, tag, attrs): def _attr(attrlist, attrname): for attr in attrlist: if attr[0] == attrname: return attr[1] return None