首页 / PYTHON / Python3批量爬取网页图片
Python3批量爬取网页图片
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python3批量爬取网页图片,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1950字,纯文字阅读大概需要3分钟。
内容图文
![Python3批量爬取网页图片](/upload/InfoBanner/zyjiaocheng/1177/32dfe6b423b84761aeccc630e1474fca.jpg)
所谓爬取其实就是获取链接的内容保存到本地。所以爬之前需要先知道要爬的链接是什么。
要爬取的页面是这个:http://findicons.com/pack/2787/beautiful_flat_icons
里面有很多不错的图标,目标就是把这些文件图片爬下来,保存成本地图片。
用python3怎么做呢?
第一步:获取要爬取的母网页的内容
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
保存目录可以自行设定。
以下是综合起来的代码:
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
原文:http://www.cnblogs.com/itlqs/p/5767054.html
内容总结
以上是互联网集市为您收集整理的Python3批量爬取网页图片全部内容,希望文章能够帮你解决Python3批量爬取网页图片所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。