首先声明一下我的这个爬虫是在unbutu16.04系统上,主要参考下面这个BLOG
https://blog.csdn.net/qq_40774175/article/details/81273198
在此基础上做了一些修改更加完善。
1,你要知道Python的requests库,利用requests 库可以获取网页的原始信息,就是你打开一个网页查看源代码所看到的那种信息 。打开某个网页鼠标右击选中view page source.(建议用Google浏览器)
Ctrl + F 搜索URL 就可以找到URL,后面对应的链接就是一个图片对应的链接(PS:本文用的是objURL)。
我们要获取到这个信息,就可以下载图片了。学习链接:https://2.python-requests.org//zh_CN/latest/user/quickstart.html
2,所以如何才能获取到这个图片的URL呢?这时候Python有一个强大的正则表达式模块,可以帮助我们找到objURL.正则表达式学习链接 https://2.python-requests.org//zh_CN/latest/user/quickstart.html
3,要下载的某种类型图片放在name.txt里面了,每次读取txt的每行内容。name.txt要跟这个程序放在同一个目录下面
此时就可以放出代码了。
# -*-coding:utf-8-*-
import re
import requests
from urllib import error
import os
num = 0
numPicture = 0
file = ''
List = []
def Find(url):
global List
print('正在检测图片总数,请稍等.....')
t = 0
i = 1
s = 0
while t < 1000: # 这里设置搜索图片数量
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) # 先利用正则表达式找到图片url
s += len(pic_url)
if len(pic_url) == 0:
break
else:
List.append(pic_url)
t = t + 60
return s
def dowmloadPicture(html, keyword):
global num
pic_url = re.findall('"objURL":"(.*?)",', html, re.S) # 先利用正则表达式找到图片url
print('找到关键词:' + keyword + '的图片,即将开始下载图片...')
for each in pic_url:
imsearch = re.search('png', each) # 筛选JPG图片
if imsearch is not None:
continue
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 = file + '/' + keyword + '_' + str(num) + '.jpg'
fp = open(string, 'wb')
fp.write(pic.content)
fp.close()
num += 1
if num >= numPicture:
num = 0 # 每个分类的下载图片数归零
return
if __name__ == '__main__': # 主函数入口
tm = int(input('请输入每类图片的下载数量 '))
numPicture = tm
line_list = []
with open('./name.txt', encoding='utf-8') as file:
line_list = [k.strip() for k in file.readlines()] # 用 strip()移除末尾的空格
for word in line_list:
if len(word) != 0: # 检查name.txt每一行
url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + '&pn='
tot = Find(url)
print('经过检测%s类图片共有%d张' % (word, tot))
file = word
y = os.path.exists(file)
if y == 1:
print('该文件已存在,请重新输入')
file = word + '文件夹2'
os.mkdir(file)
else:
os.mkdir(file)
t = 0
tmp = url
while t < numPicture:
try:
url = tmp + str(t)
result = requests.get(url, timeout=10)
print(url)
except error.HTTPError as e:
print('网络错误,请调整网络后重试')
t = t + 60
else:
dowmloadPicture(result.text, word)
t = t + 60
else:
print('当前搜索结束,感谢使用')