Python3批量爬取网页图片(小爬虫)

简介

操作系统:window 10
开发环境:Python 3.6.13
开发IDE :PyCharm

所谓爬取其实就是获取链接的内容保存到本地。所以爬之前需要先知道要爬的链接是什么。

本期要爬取的页面是这个:http://findicons.com/pack/2787/beautiful_flat_icons

这里写图片描述

我们爬去这个网页上面这些不错的图标。

第一步:获取要爬取的母网页的内容

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

你实现了吗?

这里写图片描述

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值