●前言
网络爬虫,也称之为蜘蛛(spider),网络传言此子万物皆可爬,实则不然,爬虫只是批量的快速的拿到别人网络上明面上给你展现的东西,而如今对于大部分爬虫来说无非就是图片、音乐、视频、文字等内容的爬取,当然这些只是明面上的东西,除了这些还有些危险的东西,咱们在这就不讨论了,小心被叫去喝茶。
今天咱们就初步看看网上的图片是如何爬取下来的。
●准备工作
1.背景介绍
遇到自己喜欢的壁纸,表情包,妹子图,还要逐张保存?嫌麻烦?不要了?这怎么可以,我们已经不是小孩子了,我们都是成年人了,小孩才做选择题,我们——全都要!
那么爬哪的图呢?
吃瓜群众:*mzitu.com?*um.cc?……
打住,大家都是遵纪守法的好公民,都是祖国未来的花朵,怎么能干这些事呢,莫不是想喝茶了?咱们就简单的爬下百度图片吧,没错,就是百度图片,滴,度娘卡!
2.爬取步骤
发起请求:
通过HTTP库向目标站点发起请求,也就是发送一个Request,等待服务器响应。
获取响应内容:
如果服务器能正常响应,会得到一个Response,Response的内容便是所要获取的页面内容,类型可能是HTML,Json字符串,二进制数据(图片或者视频)等类型
解析内容:
得到的内容可能是HTML,可以用正则表达式,页面解析库进行解析,可能是Json,可以直接转换为Json对象解析,可能是二进制数据,可以做保存或者进一步的处理
保存数据:
保存形式多样,保存至本地,数据库,或者特定格式的文件。
3.BeautifulSoup4
BeautifulSoup4,一款非常强大的python库,简直就是爬虫利器,也是爬虫必学的技能之一。BeautifulSoup4主要用来解析HTML/XML,一般配合lxml使用,当然,配合python内置的解析器也可以使用。
pip install beautifulsoup4 # cmd安装BeautifulSoup4
# 或者
easy_install beautifulsoup4
●小试牛刀
人狠话不多,接下来咱们就正式开始爬取:
1.分析链接构造,模拟请求
打开百度图片,搜索框输入‘壁纸’,提取主要链接为:http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=搜索内容&pn=,模拟请求:
import requests
url = http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=壁纸&pn=60 # pn显示结果的页数
result = requests.get(url, timeout=7)
print(result.text)
2.获取响应内容,解析内容
找到图片真实链接:
复制打开看下
通过链接可以看出,我们只需要获取"objURL":“和”,中间的内容,那么用正则可以轻松匹到:
result = result.text
pic_url = re.findall('"objURL":"(.*?)",', result, re.S)
除了正则的方式,用BeautifulSoup也是可以获取的,下面我们用BeautifulSoup来解析网页,获取下相关搜索的内容:
打开调试,我们可以看到相关搜索的内容是在一个名为topRS的div里的所有a标签的文本,接下来我们就来用bs4获取它们:
from bs4 import BeautifulSoup
url = http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=壁纸&pn=60 # pn显示结果的页数
html = requests.get(url)
html.encoding = 'utf-8'
bsobj = BeautifulSoup(html.text, 'html.parser')
div = bsobj.find('div', id='topRS')
lista = div.findAll('a')
re = []
for i in lista:
re.append(i.get_text())
3.保存内容(以一张为例)
pic_url = "http://e.hiphotos.baidu.com/zhidao/pic/item/5d6034a85edf8db12f74f3fa0923dd54574e74d2.jpg"
pic = requests.get(pic_url, timeout=7)
# 将获取的内容保存为后缀为jpg的图片
fp = open("picture.jpg", "wb")
fp.write(pic.content)
fp.close()
# 或者
with open("picture.jpg", "wb") as fp:
fp.write(pic.content)
fp.close()
附上完整代码:
import re
import requests
from urllib import error
from bs4 import BeautifulSoup
import os
num = 0
numPicture = 0
List = []
class CrawlingPictures(object):
"""批量下载图片"""
def __int__(self):
self.__init__()
def count(self, url):
global List
print('正在检测图片总数,请稍等.....')
t = 0
i = 1
s = 0
while t < 20000:
Url = url + str(t)
try:
result = requests.get(Url, timeout=7)
except BaseException:
t = t + 60
continue
else:
result = result.text
pic_url = re.findall('"objURL":"(.*?)",', result, re.S)
s += len(pic_url)
if len(pic_url) == 0:
break
else:
List.append(pic_url)
t = t + 60
return s
def recommend(self, url):
re = []
try:
html = requests.get(url)
except error.HTTPError as e:
return
else:
html.encoding = 'utf-8'
bsobj = BeautifulSoup(html.text, 'html.parser')
div = bsobj.find('div', id='topRS')
if div is not None:
lista = div.findAll('a')
for i in lista:
if i is not None:
re.append(i.get_text())
return re
def dowmloadpicture(self, html, keyword, path, numpicture):
global num
pic_url = re.findall('"objURL":"(.*?)",', html, re.S) # 先利用正则表达式找到图片url
print('找到关键词:' + keyword + '的图片,即将开始下载图片...')
for each in pic_url:
print('正在下载第' + str(num + 1) + '张图片,图片地址:' + str(each))
try:
if each is not None:
pic = requests.get(each, timeout=7)
else:
continue
except BaseException:
print('错误,当前图片无法下载')
continue
else:
string = path + r'\\' + keyword + '_' + str(num) + '.jpg'
fp = open(string, 'wb')
fp.write(pic.content)
fp.close()
num += 1
if num >= numpicture:
return
def run(self):
self.hello()
word = input("请输入搜索关键词: ")
url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + '&pn='
pictrecount = self.count(url)
recommend = self.recommend(url)
print('%s类图片共有%d张' % (word, pictrecount))
numpicture = int(input('请输入想要下载的图片数量 '))
save_dir = input('请输入保存路径,如E:\downloads,默认保存至桌面请输入1')
if save_dir == '1':
save_dir = r'C:\Users\Administrator\Desktop'
file = input('请建立一个存储图片的文件夹,输入文件夹名称即可,例如 背景')
files = './' + file
try:
os.makedirs(save_dir + files)
except Exception as e:
print('该文件已存在,请重新输入')
file = input('请建立一个存储图片的文件夹,输入文件夹名称即可,例如 背景')
files = './' + file
os.makedirs(save_dir + files)
else:
pass
path = save_dir + files
t = 0
tmp = url
while t < numpicture:
try:
url = tmp + str(t)
result = requests.get(url, timeout=10)
except error.HTTPError as e:
print('网络错误,请调整网络后重试')
t = t + 60
else:
self.dowmloadpicture(result.text, word, path, numpicture)
t = t + 60
print('图片下载完成,感谢使用')
print('猜你喜欢')
for re in recommend:
print(re, end=' ')
def hello(self):
print('*' * 80)
print('\t\t\t\t图片批量下载小助手')
print('\t\t\t\t作者:Charles Wang')
print('*' * 80)
if __name__ == '__main__':
Pictures = CrawlingPictures()
Pictures.run()
效果图和结果:
打包之后的exe文件和源码放在了百度网盘,有兴趣的朋友可以下载
链接:
https://pan.baidu.com/s/1HkBQxWSlCG7wwV3D-nJcxQ
提取码:7gm5
●后记
本文测试下载50张图片耗时10s,如果采用多线程或者分布式会更快,当然不建议这样,并发量过大可能会给别人服务器造成不小压力,我们要做一个文明的spider。
对python感兴趣的朋友们可以扫码关注公众号,会不定时更新一些python基础、网络爬虫、数据分析等知识,也欢迎大家前来探讨交流,公众号加星标,不迷路!
最后安利一个免费看视频的网站:https://www.cvengineer.cn