requests+re
通过requests库进行请求,然后用正则匹配图片的URL,然后再进行图片的保存。
import re
import requests
from bs4 import BeautifulSoup
# 指定url
url = 'https://image.baidu.com/search/index'
# 参数
s=input('请输入要查找的图片:')
param={
'tn': 'baiduimage',
'ps': 1,
'ct': 201326592,
'lm': -1,
'cl': 2,
'nc': 1,
'ie': 'utf-8',
'word': s
}
# 请求头
#有时候只有user-agent还是不行的。
header = {
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
'Access-Control-Allow-Credentials': 'true',
'Connection': 'keep-alive',
'Accept-Language': 'zh-CN,zh;q=0.9'
}
r=requests.get(url,params=param,headers=header)
link=re.findall('"thumbURL":"(.*?)"',r.text) #找出图片的url链接 这里不是惰性匹配的话,会匹配到其他不相干的东西
count=0 #用来计数的
for i in link: #link是一列表
print(i)
# 对这些图片进行保存
for j in link:
count+=1
res=requests.get(j,headers=header)
with open('C:\\Users\\这里是马赛克\\Desktop\\百度图片\\s{}.jpg'.format(count),'wb') as fp:
fp.write(res.content)
r.close()
res.close()
运行效果:
只用requests
利用动态加载数据包,得到图片的URL
import re
import requests
from bs4 import BeautifulSoup
# 指定url
url='https://image.baidu.com/search/acjson'
# 参数
obj=input('要查找的图片是:')
param={
'tn': 'resultjson_com',
'logid': 7404155273977471214,
'ipn': 'rj',
'ct': 201326592,
'fp': 'result',
'queryWord': obj,
'cl': 2,
'lm': -1,
'ie': 'utf-8',
'oe': 'utf-8',
'word': obj,
'nc': 1,
'pn': 0, #前面已展示的图片数量
'rn': 30, #要申请展示的图片数量
'gsm': '1e'
}
# 请求头
header = {
# 'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
'Access-Control-Allow-Credentials': 'true',
'Connection': 'keep-alive',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Referer':'https://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E5%B0%8F%E7%A7%98'
}
r=requests.get(url,params=param,headers=header)
data=r.json()['data'] #是一列表
count=0
url_list=[] #存图片的url
for i in data[0:30]: #data[30]是个空字典
count=count+1
print(i["thumbURL"])
url_list.append(i['thumbURL'])
print(count)
#进行图片的存储
k=0
filename='C:\\Users\\马赛克马赛克\\Desktop\\百度图片\\'+obj
for i in url_list:
k=k+1
res=requests.get(i,headers=header)
with open(filename+'{}.jpg'.format(k),'wb') as fp:
fp.write(res.content)
运行效果: