所谓爬取其实就是获取连接的内容保存到本地。因此爬以前须要先知道要爬的连接是什么。python
要爬取的页面是这个:http://findicons.com/pack/2787/beautiful_flat_iconsweb
里面有不少不错的图标,目标就是把这些文件图片爬下来,保存成本地图片。app
用python3怎么作呢?url
第一步:获取要爬取的母网页的内容spa
import urllib.request import re url = "http://findicons.com/pack/2787/beautiful_flat_icons" webPage=urllib.request.urlopen(url) data = webPage.read() data = data.decode('UTF-8')
第二步:对母网页内容处理,提取出里面的图片连接3d
k = re.split(r'\s+',data) s = [] sp = [] si = [] for i in k : if (re.match(r'src',i) or re.match(r'href',i)): if (not re.match(r'href="#"',i)): if (re.match(r'.*?png"',i) or re.match(r'.*?ico"',i)): if (re.match(r'src',i)): s.append(i) for it in s : if (re.match(r'.*?png"',it)): sp.append(it)
第三步:获取这些图片连接的内容,并保存成本地图片code
cnt = 0 cou = 1 for it in sp: m = re.search(r'src="(.*?)"',it) iturl = m.group(1) print(iturl) if (iturl[0]=='/'): continue; web = urllib.request.urlopen(iturl) itdata = web.read() if (cnt%3==1 and cnt>=4 and cou<=30): f = open('d:/pythoncode/simplecodes/image/'+str(cou)+'.png',"wb") cou = cou+1 f.write(itdata) f.close() print(it) cnt = cnt+1
保存目录能够自行设定。blog
如下是综合起来的代码:图片
import urllib.request import re url = "http://findicons.com/pack/2787/beautiful_flat_icons" webPage=urllib.request.urlopen(url) data = webPage.read() data = data.decode('UTF-8') k = re.split(r'\s+',data) s = [] sp = [] si = [] for i in k : if (re.match(r'src',i) or re.match(r'href',i)): if (not re.match(r'href="#"',i)): if (re.match(r'.*?png"',i) or re.match(r'.*?ico"',i)): if (re.match(r'src',i)): s.append(i) for it in s : if (re.match(r'.*?png"',it)): sp.append(it) cnt = 0 cou = 1 for it in sp: m = re.search(r'src="(.*?)"',it) iturl = m.group(1) print(iturl) if (iturl[0]=='/'): continue; web = urllib.request.urlopen(iturl) itdata = web.read() if (cnt%3==1 and cnt>=4 and cou<=30): f = open('d:/pythoncode/simplecodes/image/'+str(cou)+'.png',"wb") cou = cou+1 f.write(itdata) f.close() print(it) cnt = cnt+1