需要第三方库requests支持
通过pip安装
cmd输入:pip install requests

通过关键字进行爬取
import json
import os
import requests
def downloadImage(keyword,begin,end,file):
id=0;
if not os.path.exists(file): # 目录不存在时,创建目录
os.makedirs(file)
for i in range(begin*30,end*30,30):
data = ({
'tn': 'resultjson_com',
'ipn': 'rj',
'queryWord': keyword,
'word': keyword,
'pn': i,
'rn': 30
})
url = 'https://image.baidu.com/search/acjson'
req=requests.get(url,params=data).json().get("data");
for it in req:
if 'thumbURL' in it and len(it['thumbURL'])>0:
print('正在下载:%s' % it['thumbURL'])
img = requests.get(it['thumbURL'])
open(file + '%d.jpg' % id, 'wb').write(img.content)
id += 1
else:
print('链接已失效')
if __name__ == '__main__':
dataList = downloadImage('星空',0,100,'d:/myImage/') # (关键字,起始页数,终止页数(30张/页),存储目录)
本文介绍了一种使用Python和requests库从百度图片搜索结果中批量下载图片的方法。通过定义一个函数,可以指定关键词、开始和结束页数以及保存路径,实现自动化图片抓取。文章详细展示了如何构造请求参数,解析JSON响应并下载图片。
1107

被折叠的 条评论
为什么被折叠?



