通过关键词爬取百度图片 |
您所在的位置:网站首页 › 如何在百度中搜索图片信息呢 › 通过关键词爬取百度图片 |
爬取百度图片
在这里我们先列出本次爬虫的步骤(思路很重要): 1、通过requests获取网页信息2、找到图片链接在哪里3、创建文件夹,将图片下载到本地在开始之前,先讲一下百度图片翻页的一个小细节(看图): 这是下滑加载更多的翻页方式(对我们的爬虫造成了干扰)![]() ![]() 那么,我们怎么把网页变成我们想要的呢?在这里教大家一个小技巧: https://image.baidu.com/search/ index ?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1550561905560_R&pv=&ic=&nc=1&z=&hd=&latest=©right=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=Python 将index改为 flip,就可以将翻页模式变成传统翻页了(很神奇吧) 进入正文啦! 第一步,requests请求class是类封装,不懂的话可以上网找下教程,或者我有空写一篇教程… import requests import os import re #word是要爬的图片名字 word=input("请输入关键词:") #j用来标记图片数量 j=1 class PaChong: # 初始化 def __init__(self,word,i): #path是图片存放的地方 self.path="F:/"+word+"/" # 第几页 self.page=i/20+1 #如果文件夹不存在,则创建文件夹 if not os.path.exists(self.path): os.mkdir(self.path) #发出requests请求 def requests_get(self,url): req=requests.get(url,timeout=30) req.encoding="utf-8" self.req=req.text 第二步,通过正则找到图片链接通过图片链接,在源代码中我们可以找到存放链接的key:objURL,这样我们就可以通过正则找出所有的链接 第三步,下载图片到本地+循环翻页爬取 链接里的word是关键词的参数,pn参数是用来翻页的 #下载图片到本地 def download(self): global j for imgurl in self.imgurls: path=self.path+word+str(j) with open(path+".jpg","wb") as f: r=requests.get(imgurl) f.write(r.content) print("%s下载成功"%path) j+=1 print("第{}页下载结束!".format(self.page)) #通过pn参数实现翻页,第一页为0,,间隔为20 for i in range(0,60,20): url="https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word={0}&pn={1}&gsm=50&ct=&ic=0&lm=-1&width=0&height=0".format(word,i) Run=PaChong(word,i) Run.requests_get(url) Run.get_imgurl() Run.download()在这里我们输入关键词:剑网三,以下是代码运行结果(会玩剑网三的博友可以带我玩呀嘻嘻): 代码整合: import requests import os import re #word是要爬的图片名字 word=input("请输入关键词:") #j用来标记图片数量 j=1 class PaChong: def __init__(self,word,i): #path是图片存放的地方 self.path="F:/"+word+"/" # 第几页 self.page=i/20+1 #如果文件夹不存在,则创建文件夹 if not os.path.exists(self.path): os.mkdir(self.path) #发出requests请求 def requests_get(self,url): req=requests.get(url,timeout=30) req.encoding="utf-8" self.req=req.text #正则找到图片链接 def get_imgurl(self): imgurls=re.findall('"objURL":"(.*?)"',self.req,re.S) self.imgurls=imgurls #下载图片到本地 def download(self): global j for imgurl in self.imgurls: path=self.path+word+str(j) #写入文件 with open(path+".jpg","wb") as f: r=requests.get(imgurl) f.write(r.content) print("%s下载成功"%path) j+=1 print("第{}页下载结束!".format(self.page)) #通过pn参数实现翻页,第一页为0,,间隔为20 for i in range(0,60,20): url="https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word={0}&pn={1}&gsm=50&ct=&ic=0&lm=-1&width=0&height=0".format(word,i) Run=PaChong(word,i) Run.requests_get(url) Run.get_imgurl() Run.download()如果这篇文章对您有用的话,可以点个赞鼓励我下再走哈哈 |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |