爬取百度图片,并把图片保存在D:\图片文件夹中。只要有安装所需的库一定可以运行。
import requests
import json
import os
word=input('请输入要下载的百度图片:')
ms=int(input('请输入要爬取图片数量(30整数倍):'))
s=0
try:
os.mkdir('D:/图片')
except:
for u in range(30,ms+1,30):
url='https://image.baidu.com/search/acjson?tn=resultjson_com&logid=12023053771822378311&ipn=rj&ct=201326592&is=&fp=result&queryWord={}&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=&hd=&latest=©right=&word={}&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&nojc=&pn={}&rn=30&gsm=78&1627724467670='.format(word,word,u)
header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"
}
text=requests.get(url=url,headers=header)
text=text.text
text=json.loads(text)
list=text['data']
s=s
for i in list:
if len(i)>0:
s = int(s)
s = s + 1
s = str(s)
try:
wordname=word+s
link=i['middleURL']
jpg=requests.get(url=link,headers=header)
ls=jpg.content
with open('D:/图片/{}.jpg'.format(wordname),'wb') as f:
f.write(ls)
f.close()
print('下载{}图片完成'.format(wordname))
except:
pass