批量自动下载图片

本文介绍了一个Python脚本,用于从百度图片搜索中批量下载图片。脚本通过输入关键词、保存地址和图片数量,自动抓取并保存图片到指定文件夹。涵盖了网页请求、正则表达式匹配和文件操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

来源于百度图片。

输入关键词,图片保存地址,图片数量,自动批量下载保存到本地文件夹。

import re
import requests
from urllib import error
from bs4 import BeautifulSoup
import os

num = 0
numPicture = 0
file = ''
List = []

l
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 recommend(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(html, keyword):
	global num
	# t =0
	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 = 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("请输入搜索关键词(可以是人名,地名等): ")
	# add = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=%E5%BC%A0%E5%A4%A9%E7%88%B1&pn=120'
	url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + '&pn='
	tot = Find(url)
	Recommend = recommend(url)  # 记录相关推荐
	print('经过检测%s类图片共有%d张' % (word, tot))
	numPicture = int(input('请输入想要下载的图片数量 '))
	file = input('请建立一个存储图片的文件夹,输入文件夹名称即可')
	y = os.path.exists(file)
	if y == 1:
		print('该文件已存在,请重新输入')
		file = input('请建立一个存储图片的文件夹,)输入文件夹名称即可')
		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

	print('当前搜索结束,感谢使用')
	print('猜你喜欢')
	for re in Recommend:
		print(re, end='  ')

代码clone时间长久,忘记了出处,如果作者看到请联系。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值