python爬虫爬取百度图片

目标:python爬虫爬取百度图片。

出现问题
成功写入第一张图片,但在写入第二张图片时报错:
FileNotFoundError: [Errno 2] No such file or directory: ‘D://pictures/httpsgimg2.baidu.comimage_searchsrc=http%3A%2F%2Fimg1.gtimg.com%2F2012%2Fpics%2Fhv1%2F77%2F60%2F1106%2F71933027.jpg&refer=http%3A%2F%2Fimg1.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpegsec=1612858069&t=60c7ba1507c78186176e96a8448a6d85.jpg’
每次运行在爬取到第一张图片并写入文件后即报以上错。

解决手段:
在写文件处加入异常处理,出现异常时跳过异常继续执行循环:
try:
with open(pictureSavePath,‘wb’) as fp:
fp.write(picture)
except:
Continue
***原因分析:对同一页面中的不同图片url,有的成功写入,有的会报错。于是我选取了成功的与报错的图片url进行分析。
成功url:
https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_match%2F0%2F10944352078%2F0.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1612863479&t=adc41ae78c49861801789985f49491d7
失败url:
https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.mp.itc.cn%2Fupload%2F20161118%2Fbce0b84835a143c2b506da3838870c5f_th.jpg&refer=http%3A%2F%2Fimg.mp.itc.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1612863479&t=7c04695c5c1570fdde25266631ae9611
https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fqiniuimg.qingmang.mobi%2Fimage%2Forion%2F74f32de53f6c7174210ca819a87cc1f4_1200_750.jpeg&refer=http%3A%2F%2Fqiniuimg.qingmang.mobi&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1612863479&t=b8adda8beea427187380d79dbb326a4c

***解决效果:***可以跳过报错问题。但大量图片并未下载到本地且下载的图片有很多重复。

在这里插入图片描述

在这里插入图片描述

源码:

import requests #首先导入库
import  re
import os
#设置默认配置
MaxSearchPage = 20 # 收索页数
CurrentPage = 1# 当前正在搜索的页数
DefaultPath = "./pictures" # 默认储存位置
NeedSave = 0 # 是否需要储存
#图片链接正则和下一页的链接正则
def imageFiler(content): # 通过正则获取当前页面的图片地址数组
          return re.findall('"objURL":"(.*?)"',content,re.S)#获取.*?中URL
def nextSource(content): # 通过正则获取下一页的网址
          next = re.findall('<div id="page">.*<a href="(.*?)" class="n">',content,re.S)[0]
          print("---------" + "http://image.baidu.com" + next) 
          return next
#爬虫主体
def spidler(source):
          headers={'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'}
          content = requests.get(source,headers=headers).text  # 通过链接获取内容
          imageArr = imageFiler(content) # 获取图片数组
          global CurrentPage
          print("Current page:" + str(CurrentPage) + "**********************************")
          for imageUrl in imageArr:
              print(imageUrl)
              global  NeedSave
              if NeedSave:  			# 如果需要保存图片则下载图片,否则不下载图片
                 global DefaultPath
                 try:
                      # 下载图片并设置超时时间,如果图片地址错误就不继续等待了
                      picture = requests.get(imageUrl,timeout=10).content#picture为返回的图片二进制数据
                 except:                
                      print("Download image error! errorUrl:" + imageUrl)   
                      continue
                 # 创建图片保存的路径
                
                 imageUrl = imageUrl.replace('/','').replace(':','').replace('?','')#将'/',':','?'替换为' '
                 pictureSavePath = DefaultPath+'/'+imageUrl+'.jpg'
                 
                 if not os.path.exists( DefaultPath):
                     os.mkdir(DefaultPath)
                 try:
                     with open(pictureSavePath,'wb') as fp:
                          fp.write(picture)
                 except:
                     continue
                     
                     
                  
                       
          global MaxSearchPage
          if CurrentPage < MaxSearchPage:    #继续下一页爬取
               if nextSource(content):
                   CurrentPage += 1 
                   # 爬取完毕后通过下一页地址继续爬取
                   spidler("http://image.baidu.com" + nextSource(content)) 
#爬虫的开启方法
def  beginSearch(page=1,save=0,savePath="D://pictures"): 
          # (page:爬取页数,save:是否储存,savePath:默认储存路径)
          global MaxSearchPage,NeedSave,DefaultPath
          MaxSearchPage = page
          NeedSave = save					#是否保存,值0不保存,1保存
          DefaultPath = savePath				#图片保存的位置
          key = input("Please input you want search:") 
          StartSource = "http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=" + str(key) + "&ct=201326592&v=flip" # 分析链接可以得到,替换其`word`值后面的数据来搜索关键词
          spidler(StartSource)
#调用开启的方法就可以通过关键词搜索图片了
beginSearch(page=5,save=1)			# page=5是下载前5页,save=1保存图片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值