首页 > 技术文章 > Crawl(2)

dirge 2017-02-11 22:12 原文

 http://cuiqingcai.com/3179.html

 1 # *-* coding: UTF-8 *-*
 2 import urllib2
 3 import cookielib
 4 import re
 5 import time
 6 import os
 7 
 8 
 9 ####################################
10 #cookie
11 cookie = cookielib.CookieJar()
12 handler = urllib2.HTTPCookieProcessor(cookie)
13 opener = urllib2.build_opener(handler)
14 #####
15 def mkdir(path):  
16     path = path.strip()  
17     # 判断路径是否存在  
18     # 存在    True  
19     # 不存在  Flase  
20     isExists = os.path.exists(path)  
21     if not isExists:  
22         print u'新建了名字叫做',path,u'的文件夹'  
23         # 创建目录操作函数  
24         os.makedirs(path)  
25         return True  
26     else:  
27         # 如果目录存在则不创建,并提示目录已经存在  
28         print u'名为',path,u'的文件夹已经创建成功'  
29         return False
30 #####
31 def saveImages(imglist,name):
32     print u'共 %s张图片' %len(imglist)
33     number = 1  
34     for imageURL in imglist:
35         fileName = name + "/" + str(number) + ".jpg"  
36         # 对于每张图片地址,进行保存  
37         try:  
38             u = urllib2.urlopen(imageURL, timeout = 10)
39             print '1'
40             data = u.read()
41             print '2'
42             f = open(fileName,'wb+')  
43             print '3'
44             f.write(data)  
45             print u'正在保存的一张图片为',fileName  
46             f.close()
47         except Exception, e:
48             print Exception,":",e
49         break
50         #保存封面,大图一般太大,截图过大,容易超时
51         number += 1  
52 #####
53 if __name__ == '__main__':
54     patter = r'<span id="thread_(\d{7})">'
55     reg = re.compile(patter)
56     for i in range(1, 5):#前5页
57         if i%10 == 0: print 'now is %s' %i
58         req = urllib2.Request('http://38.103.161.179/forum/forumdisplay.php?fid=230&filter=type&typeid=172&page=%s' %str(i))
59         html = unicode(opener.open(req).read(), 'gbk')
60         tar = reg.findall(html)
61         
62         for jpos, j in enumerate(tar):#遍历所有子链接
63             req2 = urllib2.Request('http://38.103.161.179/forum/viewthread.php?tid='+j)
64             html2 = unicode(opener.open(req2).read(), 'gbk')
65             endpos = html2.index(u'附件</h4>')
66             stapos = html2.index(u'格式')
67             html2 = html2[stapos:endpos]
68             #print html2
69             patter2 = r'src="(.+?\.jpg)"' 
70             reg2 = re.compile(patter2)
71             tar2 = reg2.findall(html2)
72             path = u'图集'+str(i)+u'之图'+str(jpos)
73             mkdir(path)
74             saveImages(tar2, path)
75     exit()
View Code

 

感谢weiyinfu学长指出。

urllib2用requests替代。

解析页面re用BeautifulSoup替代。

scrapy框架。

遇到验证码,用PIL,opencv,pybrain等。

多线程threading,python并行库框架celery。

推荐阅读