Python学习笔记之网络爬虫
网络爬虫的实现可以用BFS(宽度优先搜索),以某个weburl为起始节点,利用标准库的SGMLParser解析html提取超链接,判重后进队,即可实现对网页的抓取。
1)用HTMLParser实现的时候编码的问题总是解决不了,很多html解析后都直接抛出异常,试过将当前html的编码格式转成unicode也无法解决。于是改为SGMLParser,便没有出现编码问题,基本上试过很多站点的html都可以正常解析。
2)关于url判重,我直接放在一个字典里面然后用has_key()找,可能效率并不高。更高效应该是用hashlib等标准库。
感觉代码实现的有点搓,有待优化。。。
#!/usr/bin/env python
import sys, socket, HTMLParser, urllib, urllib2
from sgmllib import SGMLParser
#analysis html file
class MyParser(SGMLParser):
def __init__(self):
self.link = []
SGMLParser.__init__(self)
def start_a(self, attrs):
for name, value in attrs:
if name == 'href' and value.startswith('h'):
self.link.append(value)
def getlink(self):
return self.link
#save html file to disk
def SaveFile(name, html):
f = file("/home/crbtmac/html/" + name, 'w')
f.write(html)
f.close()
def doit():
WebUrl = ['http://www.baidu.com']
value = 0
dic = {}
id = 0
while len(WebUrl) > 0:
try:
if len(WebUrl):
url1 = WebUrl.pop(0)
req = urllib2.Request(url1)
id += 1
except urllib2.URLError, e:
print e
try:
#open the weburl
fd = urllib2.urlopen(req)
Html = fd.read()
#save html file to disk
name = str(id) + '.html'
SaveFile(name, Html)
parser = MyParser()
parser.feed(Html)
#get the link from current page
Link = parser.getlink()
for url in Link:
if dic.has_key(url) == False:
dic[url] = value
WebUrl.append(url)
value += 1
except:
print 'Error'
continue
if __name__ == '__main__':
doit()