admin 管理员组文章数量: 1086019
python常用小技巧(一)——百度图片批量爬取
python常用小技巧(一)——百度图片无限制批量爬取
前言:我们在日常使用(搜壁纸,搜美女~~)或者科研项目(图像识别)中经常要批量获取某种类型的图片,然而很多时候我们都需要一个个点击下载,有什么办法可以让程序替我们完成这项工作呢,那就是爬虫啦。
一、准备材料:
- Python
- os
- re
- time
- random
- request
二、爬取难点:
百度拥有反爬虫机制,网上很多爬虫程序只能爬取30张(一页)图片。
这个时候你就要说了,一页页递增地遍历不就可以获取多页的图片了吗?
我一开始也这样想,后面发现百度页面没有分页,网址没有页数可以让我们改。
在搜索了许多网上那个的资料后,我终于找到了可以一页页递增地遍历的爬虫,当我满心欢喜地运行完之后,我发现我下载的图片数量远没有达到我设置的页数目标。这又是为什么呢?
后来,我发现是爬虫爬取的速度太快了,百度的后台会识别出它是程序在操作而不是人为地在下载,所以当爬取到一定数量的图片后,百度后台就拒绝我的请求了。
那就没有办法了吗,如何绕过后台的监测呢?
......
办法可能有,但是我这种菜鸡就算了哈哈,但是,虽然我们绕不过后台的监测,但是我们可以骗过后台的监测呀。
怎么骗呢,办法简单到你无法想象!!
就是在请求过去下载链接的时候增加一个延时函数,而延时的时间又是由random函数产生的,那么系统不就很难发现这是程序操作了吗!
三、程序编写:
# -*- coding:utf-8 -*-
import requests
import os
import re
import time
import random
def getManyPages(keyword,pages):params=[]for i in range(30,30*pages+30,30):params.append({'tn': 'resultjson_com','ipn': 'rj','ct': 201326592,'is': '','fp': 'result','queryWord': keyword,'cl': 2,'lm': -1,'ie': 'utf-8','oe': 'utf-8','adpicid': '','st': -1,'z': '','ic': 0,'word': keyword,'s': '','se': '','tab': '','width': '','height': '','face': 0,'istype': 2,'qc': '','nc': 1,'fr': '','pn': i,'rn': 30,'gsm': '1e','1488942260214': ''})url = ''# regex = repile(r'\\(?![/u"])')# new_url = regex.sub(r"\\\\", url)urls = []#for i in params :# new_params = regex.sub(r"\\\\", params[i])for i in params:
# regex = repile(r'\\(?![/u"])')
# fixed = regex.sub(r"\\\\", params[i])urls.append(requests.get(url,params=i).json().get('data'))return urlsdef getpage(key,page):new_url = []for i in range(0, page*30+30, 30):new_url.append({'tn': 'resultjson_com','ipn': 'rj','ct': 201326592,'is': '','fp': 'result','queryWord': key,'cl': 2,'lm': -1,'ie': 'utf-8','oe': 'utf-8','adpicid': '','st': -1,'z': '','ic': 0,'word': key,'s': '','se': '','tab': '','width': '','height': '','face': 0,'istype': 2,'qc': '','nc': 1,'fr': '','pn': i,'rn': 30,'gsm': '1e','1488942260214': ''})url = ''result=[]for i in new_url:randnumber1 = random.randint(0,3)#生成随机数time.sleep(randnumber1)#按随机数延时print(i)try:result.append(requests.get(url, params=i).json().get('data'))print(result)except :#如果延时之后还是被拒绝#print('error\n')randnumber2 = random.randint(5,10)#延迟随机时间time.sleep(randnumber2)#print(result)return resultdef getImg(dataList, localPath,keyword):i=1x = 0for list in dataList:for each in list:###################try:if each.get('thumbURL') != None:print('downloading:%s' % each.get('thumbURL'))pic = requests.get(each.get('thumbURL'))except requests.exceptions.ConnectionError:print('error: This photo cannot be downloaded')continuedir = 'image/' + keyword + '_' + str(i) + '.jpg'fp = open(dir, 'wb')fp.write(pic.content)fp.close()i += 1def dowmloadPic(html, keyword):pic_url = re.findall('"objURL":"(.*?)",', html, re.S)i = 1print('Can not find key word:' + keyword + 'is downloading...')for each in pic_url:print('No ' + str(i) + '.jpg is downloading ,URL:' + str(each))try:pic = requests.get(each, timeout=10)except requests.exceptions.ConnectionError:print('error: This photo cannot be downloaded')continuedir = 'image/' + keyword + '_' + str(i) + '.jpg'fp = open(dir, 'wb')fp.write(pic.content)fp.close()i += 1if __name__ == '__main__':# dataList = getManyPages('shoes',10) # key word and number of page# getImg(dataList,'/image') # pathkeyword = 'shoes' #改变keyword就可以得到你要搜索的图片dataList = getpage(keyword,50) # key word and number of pagegetImg(dataList,'/images',keyword) # path
四、程序运行与结论
我们可以看到程序已经爬取了1422张图片
虽然理论上这个傻办法是可以骗过后台的,但是有些时候还是会被拦截,大家可能要多尝试几遍才能得到想要的数量
本文标签: python常用小技巧(一)百度图片批量爬取
版权声明:本文标题:python常用小技巧(一)——百度图片批量爬取 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/b/1693587761a230878.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论