您的位置:首页 > 编程语言 > Python开发

Python爬虫实战(二) — 百度图片下载器

2018-02-24 12:46 274 查看

前言

上一次编写了一个Pixabay的图片下载器,但是,因为Pixabay的服务器在国外,下载速度上远远达不到效果,这次我们编写一个大家常用的百度图片的下载器,有了之前的经验后,这次就变得异常简单了。

本篇目标

根据关键词搜索图片,并提取链接

实现自动下载图片,并保存到指定文件夹下

若文件夹不存在,实现自动创建功能

快速开始

1.确定URL并抓取页面源码

首先我们确定好页面的URL是

http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=贡桔&ct=201326592&v=flip


可以观察到贡桔是我们的关键词

还是老的套路,首先我们需要提取页面,并获得源码

def __init__(self):
self.keyword = input('欢迎使用百度图片下载器\n请输入搜索关键词:')
self.siteURL = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + str(
self.keyword) + '&ct=201326592&v=flip'

def getSource(self):
url = self.siteURL
result = requests.get(url).text
return result


2.提取图片网址



刚打开百度图片时,默认是瀑布流版本,为了方便我们提取图片链接,切换为右上角的传统翻页版本,点击F12打开开发者工具,可以看到其中一张图片的源地址



复制这个地址,右键网页查看网页源代码,搜索这个地址



可以看到图片一共对应了三中不同的地址,经过一一查看,我们可以发现objURL地址所对应的图片最大最清晰,接下来,我们就提取这个地址。

首先,编写正则表达式

re.compile(‘“objURL”:”(.*?)”,’, re.S)

这个很容易,然后我们完善一下代码块,返回图片地址的列表

def getItem(self):
result = self.getSource()
pattern1 = re.compile('"objURL":"(.*?)",', re.S)
items = re.findall(pattern1, result)
return items


4.保存图片

这里直接贴出来代码

def saveImage(self, item, name):
picture = urllib.request.urlopen(item)
fileName = name + '.jpg'
string = 'D:\Cloud\%s\%s' % (self.path, fileName)
E = os.path.exists(string)
if not E:
f = open(string, 'wb')
f.write(picture.read())
f.close()
else:
print('图片已经存在,跳过!')
return False

def makeDir(self, path):
self.path = path.strip()
E = os.path.exists(os.path.join('D:\Cloud', self.path))
if not E:
os.makedirs(os.path.join('D:\Cloud', self.path))
os.chdir(os.path.join('D:\Cloud', self.path))
print('成功创建名为', self.path, '的文件夹')
return self.path
else:
print('名为', self.path, '的文件夹已经存在...')
return False

def savePicture(self):
i = 0
items = self.getItem()
print ('找到关键词:'+self.keyword+'的图片,现在开始下载图片...')
self.makeDir(path=self.keyword)
for item in items:
print ('正在下载第'+str(i+1)+'张图片,图片地址:'+str(item))
try:
pic = requests.get(item, timeout=10)
except requests.exceptions.ConnectionError:
print ('【错误】当前图片无法下载')
continue
self.saveImage(item, name=self.keyword+'_' + str(i))
i += 1


完整代码如下

import re
import os
import requests
import urllib
import time

class BaiduSpider():

9df3
def __init__(self): self.keyword = input('欢迎使用百度图片下载器\n请输入搜索关键词:') self.siteURL = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + str( self.keyword) + '&ct=201326592&v=flip' def getSource(self): url = self.siteURL result = requests.get(url).text return result
def getItem(self): result = self.getSource() pattern1 = re.compile('"objURL":"(.*?)",', re.S) items = re.findall(pattern1, result) return items
def saveImage(self, item, name): picture = urllib.request.urlopen(item) fileName = name + '.jpg' string = 'D:\Cloud\%s\%s' % (self.path, fileName) E = os.path.exists(string) if not E: f = open(string, 'wb') f.write(picture.read()) f.close() else: print('图片已经存在,跳过!') return False def makeDir(self, path): self.path = path.strip() E = os.path.exists(os.path.join('D:\Cloud', self.path)) if not E: os.makedirs(os.path.join('D:\Cloud', self.path)) os.chdir(os.path.join('D:\Cloud', self.path)) print('成功创建名为', self.path, '的文件夹') return self.path else: print('名为', self.path, '的文件夹已经存在...') return False def savePicture(self): i = 0 items = self.getItem() print ('找到关键词:'+self.keyword+'的图片,现在开始下载图片...') self.makeDir(path=self.keyword) for item in items: print ('正在下载第'+str(i+1)+'张图片,图片地址:'+str(item)) try: pic = requests.get(item, timeout=10) except requests.exceptions.ConnectionError: print ('【错误】当前图片无法下载') continue self.saveImage(item, name=self.keyword+'_' + str(i)) i += 1
if __name__ == '__main__':
spider = BaiduSpider()
spider.savePicture()


Github版本

Github代码

运行结果



小结

希望大家都能尊重我的付出,转载我的文章请注明出处。

最后,也希望大家关注我的个人博客 HD Blog

谢谢~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: