作为一名优质粉,接下来的内容还是以李现为素材,真怕那一天律师函警告。
步骤:
- 分析网页,找寻网址规律
- 组织代码
- 下载图片到本地文件夹
首先,百度搜索李现图片,右键检查进入网页开发者模式,图片都是动态加载的,图片红色圈内为主要分析内容
接下来,分别点击前三条内容,分析其url有什么共同点
https://image.baidu.com/search/acjson?tn=resultjson_com&logid=11672761728025656564&ipn=rj&ct=201326592&is=&fp=result&queryWord=%E6%9D%8E%E7%8E%B0&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=&hd=&latest=©right=&word=%E6%9D%8E%E7%8E%B0&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&nojc=&pn=30&rn=30&gsm=1e&1627880953593=
https://image.baidu.com/search/acjson?tn=resultjson_com&logid=11672761728025656564&ipn=rj&ct=201326592&is=&fp=result&queryWord=%E6%9D%8E%E7%8E%B0&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=&hd=&latest=©right=&word=%E6%9D%8E%E7%8E%B0&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&nojc=&pn=60&rn=30&gsm=3c&1627880953685=
经过对比发现,网址里面有一个&pn和&gsm,其中,&pn代表偏移量,也就是一页中有30张图片,第一页&pn=30,第二页&pn=60,以此类推。
&gsm是偏移量的十六进制形式。
发现规律后,便可以开始写代码了!
源码:
# -*- coding: UTF-8 -*-
import requests
import os
import time
import re
header={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101'
' Safari/537.36 Edg/91.0.864.48',
'referer':'https://image.baidu.com/search/index?'
}
def get_url():
resp=requests.get(url,headers=header)
return resp.text
def parse_url(html,keyword):
i=1#表示图片序号
image_url=re.findall('"thumbURL":"(.*?)",',html,re.S)#正则表达式,找出图片url
for item in image_url:
print(item)#输出图片url
image=requests.get(item)#对图片url进行解析
dir=r'D:\百度图片\a'+str(keyword)+str(pn)+'_'+str(i)+'.jpg'#保存路径
#创建目录,目录不存在则创建
if not os.path.exists('D:\百度图片'):
os.makedirs('D:\百度图片')
f=open(dir,'wb')
f.write(image.content)#写入
f.close()
i=i+1
#print(item)
#主函数
if __name__=='__main__':
keyword = input('请输入图片关键词:')#输入关键词
print('开始下载:')
for pn in range(30,121,30):#pn从30开始遍历,即30,60,120
'''
format:函数用于字符串的格式化,用{}按顺序表示
hex:将10进制数转16进制
'''
url = 'https://image.baidu.com/search/acjson?tn=resultjson_com&logid=10653214222154789271&ipn=rj&ct=201326592&is=' \
'&fp=result&queryWord={}&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=&z=&ic=&hd=&latest=©righ' \
't=&word={}&s=&se=&tab=&width=&height=&face=&istype=&qc=&nc=1&fr=&expermode=&nojc=&pn={}&rn=30' \
'&gsm={}&1627870247176='.format(keyword,keyword,pn,hex(pn))
html=get_url()
parse_url(html,keyword)
time.sleep(2)#睡眠
效果图:
细心的小哥可能会发现,输入想要的关键词岂不起飞,我可没教你们,请节制,哈哈哈哈哈哈