---
title: "抓取网页并解析HTML"
author: "vergilwang"
date: "2012-08-09T16:53:00Z"
tags: []
categories: ["开源软件"]
slug: "html"
draft: false
lastmod: "2014-02-15T16:03:53Z"
id: 2011337
url: "https://vergilwang.iteye.com/blog/2011337"
---

[http://www.lovelucy.info/python-crawl-pages.html](http://www.lovelucy.info/python-crawl-pages.html)

我觉得java太啰嗦，不够简洁。Python这个脚本语言开发起来速度很快，一个活生生的例子是因有关政策verycd开始自我阉割，有网友为了抢救资源，把整个verycd站爬了下来，镜像为[SimpleCD.org](http://www.simplecd.org/ "SimpleCD")。看了一下爬虫[源代码](http://fayaa.com/code/view/15377/)，其实挺简单。使用方法：

import urllib2  
content = urllib2.urlopen('http://XXXX').read()

这样可以得到整个html文档，关键的问题是我们可能需要从这个文档中获取我们需要的有用信息，而不是整个文档。这就需要解析充满了各种标签的html。

## 2. 解析html

SGMLParser

Python默认自带HTMLParser以及SGMLParser等等解析器，前者实在是太难用了，我就用SGMLParser写了一个示例程序：

import urllib2  
from sgmllib import SGMLParser

class ListName(SGMLParser):  
def \_\_init\_\_(self):  
SGMLParser.\_\_init\_\_(self)  
self.is\_h4 = ""  
self.name = \[]  
def start\_h4(self, attrs):  
self.is\_h4 = 1  
def end\_h4(self):  
self.is\_h4 = ""  
def handle\_data(self, text):  
if self.is\_h4 == 1:  
self.name.append(text)

content = urllib2.urlopen('http://list.taobao.com/browse/cat-0.htm').read()  
listname = ListName()  
listname.feed(content)  
for item in listname.name:  
print item.decode('gbk').encode('utf8')

 

很简单，这里定义了一个叫做ListName的类，继承SGMLParser里面的方法。使用一个变量is\_h4做标记判定html文件中的h4标签，如果遇到h4标签，则将标签内的内容加入到List变量name中。解释一下start\_h4()和end\_h4()函数，他们原型是SGMLParser中的

start\_tagname(self, attrs)  
end\_tagname(self)

tagname就是标签名称，比如当遇到&lt;pre&gt;，就会调用start\_pre，遇到&lt;/pre&gt;，就会调用 end\_pre。attrs为标签的参数，以\[(attribute, value), (attribute, value), ...]的形式传回。

 

pyQuery

[pyQuery](http://pypi.python.org/pypi/pyquery "pyquery")是jQuery在python中的实现，能够以jQuery的语法来操作解析HTML文档，十分方便。使用前需要安装，easy\_install pyquery即可，或者

**sudo****apt-get** **install** python-pyquery

以下例子：

from pyquery import PyQuery as pyq  
doc=pyq(url=r'http://list.taobao.com/browse/cat-0.htm')  
cts=doc('.market-cat')

for i in cts:  
print '====',pyq(i).find('h4').text() ,'===='  
for j in pyq(i).find('.sub'):  
print pyq(j).text() ,  
print '\\n'

 

BeautifulSoup

有个头痛的问题是，大部分的网页都没有完全遵照标准来写，各种莫名其妙的错误令人想要找出那个写网页的人痛打一顿。为了解决这个问题，我们可以选择著名的BeautifulSoup来解析html文档，它具有很好的容错能力。

BeautifulSoup功能强大，我还在研究中，有进展会更新本文。