import re
import requests
from urllib import error
import os
num = 0
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"}
def dowmloadPicture(html, keyword):
global num
pic_url = re.findall('"objURL":"(.*?)"', html, re.S)
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 = file + r'\\' + keyword + '_' + str(num) + '.jpg'
fp = open(string, 'wb')
fp.write(pic.content)
fp.close()
num += 1
if num >= numPicture:
return
if __name__ == '__main__':
word = input("请输入搜索关键词(可以是人名,地名等): ")
url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + '&pn='
numPicture = int(input('请输入想要下载的图片数量:'))
file = input('请建立一个存储图片的文件夹,输入文件夹名称即可:')
while os.path.exists(file) == 1:
print('该文件已存在,请重新输入')
file = input('请建立一个存储图片的文件夹,输入文件夹名称即可:')
os.mkdir(file)
t = 0
tmp = url
while t < numPicture:
try:
url = tmp + str(t)
result = requests.get(url, timeout=10,headers = headers)
print(url)
except error.HTTPError:
print('网络错误,请调整网络后重试')
t = t + 60
else:
dowmloadPicture(result.text,word)
t = t + 60
print('当前搜索结束,感谢使用')