1
#
-*- coding: UTF-8 -*-
2
import
re
3
import
urllib2
4
5
from collections import deque
6 7# 保存文件的后缀 8 SUFFIX=‘.html‘ 9# 提取文章标题的正则表达式10 REX_TITLE=r‘<title>(.*?)</title>‘11# 提取所需链接的正则表达式12 REX_URL=r‘/jdbc/(.+?).html‘13# 种子url,从这个url开始爬取14 BASE_URL=‘http://www.yiibai.com/jdbc/‘151617# 将获取到的文本保存为html文件18def saveHtml(file_name,file_content):
19# 注意windows文件命名的禁用符,比如 /20 with open(file_name.replace(‘/‘, ‘_‘)+SUFFIX,"wb") as f:
21# 写文件用bytes而不是str,所以要转码22 f.write(file_content)
23# 获取文章标题24def getTitle(file_content):
25 linkre=re.search(REX_TITLE,file_content)
26if(linkre):
27print (‘获取文章主题:‘+linkre.group(1))
28return linkre.group(1)
2930# 爬虫用到的两个数据结构,队列和集合31 queue=deque()
32 visited=set()
33# 初始化种子链接 34queue.append(BASE_URL)
35 count=0
3637while queue:
38 url=queue.popleft() # 队首元素出队39 visited |= {url} # 标记为已访问4041print(‘已经抓取: ‘+ str(count)+‘ 正在抓取 <--- ‘+url)
42 count += 1
43 urlop=urllib2.urlopen(url)
44# 只处理html链接45if‘html‘notin urlop.headers.getheader(‘Content-Type‘):
46continue47# 避免程序异常中止48try:
49 data=urlop.read()
50 title=getTitle(data).decode(‘utf-8‘);
51# 保存文件52 saveHtml(title,data)
53except:
54continue5556# 正则表达式提取页面中所有链接, 并判断是否已经访问过, 然后加入待爬队列57 linkre = re.compile(REX_URL)
58for sub_link in linkre.findall(data):
59 sub_url=BASE_URL+sub_link+SUFFIX;
60# 已经访问过,不再处理61if sub_url in visited:
62pass63else:
64# 设置已访问65 visited |= {sub_url}
66# 加入队列67 queue.append(sub_url)
68print(‘join the quene---> ‘+sub_url)
http://blog.csdn.net/wangshihui512/article/details/51100605#python
22 和 49行 与原文有所出处 如果添加了反而无法执行 可能和编码有关系
原文:http://www.cnblogs.com/zhuzhuqwa/p/6391738.html
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!