最近加入了斗图群,发现自己的表情包太少了,斗不过他们。今天用Python实现批量抓取百度图片里面的表情包和他们决战。
需要实现的效果图:
源代码
我们所需要的信息都已经找到,那么开始编写代码吧
import requests
class Spider(object):
def __init__(self):
# 初始化headers
self.headers = {
"User-Agent": "Mozilla/5.0 (macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/80.0.3987.149 Safari/537.36"
}
# 指定存储路径
self.path = '/Users/admin/Desktop/Image/'
self.page = int(input('请输入需要爬取的页数:'))
# 获取翻页url
def get_parse_url(self):
urls =[]
for i in range(1,self.page+1):
urls.append('https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryword=%E8%A1%A8%E6%83%85%E5%8C%85&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=&z=&ic=&hd=&latest=©right=&word=%E8%A1%A8%E6%83%85%E5%8C%85&s=&se=&tab=&width=&height=&face=&istype=&qc=&nc=&fr=&expermode=&force=&pn={}&rn=30&gsm=1e&1586570843561='.format(30*i))
return urls
# 获取图片url
def get_immage_url(self,urls):
image_url = []
for url in urls:
response = requests.get(url,headers=self.headers).json()
results = response.get('data')
for i in results:
image_url.append(i.get('thumbURL'))
return image_url
# 存储
def storage_image(self,image_url):
i = 1 # 图片编号标记
for img_url in image_url:
print('正在爬取第{}张'.format(i))
if img_url is None:
continue
response = requests.get(img_url,headers=self.headers).content
with open(self.path + '{}.jpg'.format(i),'wb') as f:
f.write(response)
i +=1
def start(self):
urls = self.get_parse_url()
image_url = self.get_immage_url(urls)
self.storage_image(image_url)
spider = Spider()
spider.start()
代码解读:
如果本文对你有帮助,帮忙转发一下呗~