python 爬取 谷歌以及百度图片

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wobeatit/article/details/79559314

      近来训练模型时由于数据集网上没有现成的,无奈之下在网上各种搜图片下载,由于之前有用python写过关于爬取网页图片的脚本,但是忘了整理。趁着本次又用了下之前写的脚本,抓紧时间整理一下有关爬取百度及谷歌图片的脚本,并进一步将程序用类封装好,尽量保证使用时的方便性。

 爬取图片前的准备工作:

一、下载Chrome浏览器 or FireFox浏览器。

二、下载针对以上两种浏览器对应的驱动,并且记住浏览器驱动在电脑中的位置,在脚本中会有该步的设置。

三、下载除去常用的爬虫依赖库之外,还有selenium依赖库,该库函数主要用于模拟鼠标的下滑以及点击按钮的作用。

----------------------------------------------------------------更新------------------------------------------------------

感谢大家在评论中的修改意见,已经给示例代码修改了些小bug,现附上修改后的代码~

 下附代码:

爬取谷歌图片(ubuntu系统下的示例代码):

#*****************************
#****** 2018 12.30  **********
#*****  Author: LQ  **********
#****** Python 3.6.7 *********
#**** 用于爬取谷歌的图片*********
#*****************************
 
#****本脚本还是存有一些问题的,没有很好解决google的反爬机制以及google的翻页问题
#*******本脚本运行时需要本机安装 Chrome 浏览器以及Chrome的驱动,同时需要selenium库的支撑********
from selenium import webdriver 
from selenium.webdriver.chrome.options import Options
import time  
import urllib.request
from bs4 import BeautifulSoup as bs
import re  
import os  
#****************************************************
base_url_part1 = 'https://www.google.com/search?q='
base_url_part2 = '&source=lnms&tbm=isch' # base_url_part1以及base_url_part2都是固定不变的,无需更改
search_query = '停车' # 检索的关键词,可自己输入你想检索的关键字
location_driver = '/home/LQ/Downloads/ChromeDriver/chromedriver' # Chrome驱动程序在电脑中的位置
 
class Crawler:
    def __init__(self):
        self.url = base_url_part1 + search_query + base_url_part2
 
    # 启动Chrome浏览器驱动
    def start_brower(self):
        chrome_options = Options()
        chrome_options.add_argument("--disable-infobars")
        # 启动Chrome浏览器  
        driver = webdriver.Chrome(executable_path=location_driver, chrome_options=chrome_options)  
        # 最大化窗口,因为每一次爬取只能看到视窗内的图片
        driver.maximize_window()  
        # 浏览器打开爬取页面  
        driver.get(self.url)  
        return driver
 
    def downloadImg(self, driver):  
        t = time.localtime(time.time())
        foldername = str(t.__getattribute__("tm_year")) + "-" + str(t.__getattribute__("tm_mon")) + "-" + \
                     str(t.__getattribute__("tm_mday")) # 定义文件夹的名字
        picpath = '/home/LQ/ImageDownload/%s' %(foldername) # 下载到的本地目录 
        # 路径不存在时创建一个
        if not os.path.exists(picpath): os.makedirs(picpath)
        # 下载图片的本地路径 /home/LQ/ImageDownload/xxx
 
        # 记录下载过的图片地址,避免重复下载  
        img_url_dic = {} 
        x = 0  
        # 当鼠标的位置小于最后的鼠标位置时,循环执行
        pos = 0     
        for i in range(1): # 此处可自己设置爬取范围
            pos = i * 500 # 每次下滚500  
            js = "document.documentElement.scrollTop=%d" %pos     
            driver.execute_script(js)  
            time.sleep(1)
            # 获取页面源码
            html_page = driver.page_source
            # 利用Beautifulsoup4创建soup对象并进行页面解析
            soup = bs(html_page, "html.parser")
            # 通过soup对象中的findAll函数图像信息提取
            imglist = soup.findAll('img', {'class':'rg_ic rg_i'})
 
            # ??这段代码问题?
            for imgurl in imglist:
                try:
                    print(x, end=' ')
                    if imgurl['src'] not in img_url_dic:
                        target = '{}/{}.jpg'.format(picpath, x)
                        # print ('Downloading image to location: ' + target + '\nurl=' + imgurl['src'])
                        img_url_dic[imgurl['src']] = '' 
                        urllib.request.urlretrieve(imgurl['src'], target)
                        time.sleep(1)
                        x += 1  
                except KeyError:
                    print("ERROR!")
                    continue
 
    def run(self):
        print('\t\t\t**************************************\n\t\t\t**\t\tWelcome to Use Spider\t\t**\n\t\t\t**************************************')  
        driver=self.start_brower()
        self.downloadImg(driver)
        driver.close()
        print("Download has finished.")
 
 
if __name__ == '__main__':  
    craw = Crawler() 
    craw.run()
   

爬取百度图片(windows系统下的示例代码):

#*****************************
#****** 2018 3.14  ***********
#*****  Author: LQ  **********
#****** Python 3.6.3 *********
#**** 用于爬取百度的图片*********
#*****************************
 
#*******本脚本运行时需要本机安装 Chrome 浏览器以及Chrome的驱动,同时需要selenium库的支撑********
from selenium import webdriver 
from selenium.webdriver.chrome.options import Options
import time  
import urllib.request
from bs4 import BeautifulSoup as bs
import re  
import os  
#****************************************************
base_url_part1 = 'https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&hs=0&xthttps=111111&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word='
base_url_part2 = '&oq=bagua&rsp=0' # base_url_part1以及base_url_part2都是固定不变的,无需更改
search_query = '停车' # 检索的关键词,可自行更改
location_driver = 'D:/download/Chrome/Chrome-driver/chromedriver.exe' # Chrome驱动程序在电脑中的位置
 
class Crawler:
	def __init__(self):
		self.url = base_url_part1 + search_query + base_url_part2
 
	# 启动Chrome浏览器驱动
	def start_brower(self):
		chrome_options = Options()
		chrome_options.add_argument("--disable-infobars")
		# 启动Chrome浏览器  
		driver = webdriver.Chrome(executable_path=location_driver, chrome_options=chrome_options)  
		# 最大化窗口,因为每一次爬取只能看到视窗内的图片
		driver.maximize_window()  
		# 浏览器打开爬取页面  
		driver.get(self.url)  
		return driver
 
	def downloadImg(self, driver):  
		t = time.localtime(time.time())
		foldername = str(t.__getattribute__("tm_year")) + "-" + str(t.__getattribute__("tm_mon")) + "-" + \
					 str(t.__getattribute__("tm_mday")) # 定义文件夹的名字
		picpath = 'D:/ImageDownload/%s' %(foldername) # 下载到的本地目录 
		# 路径不存在时创建一个 
		if not os.path.exists(picpath): os.makedirs(picpath)
		# 记录下载过的图片地址,避免重复下载  
		img_url_dic = {} 
		x = 0  
		# 当鼠标的位置小于最后的鼠标位置时,循环执行
		pos = 0     
		for i in range(1): # 此处可自己设置爬取范围,本处设置为1,那么不会有下滑出现
			pos += 500 # 每次下滚500  
			js = "document.documentElement.scrollTop=%d" %pos    
			driver.execute_script(js)  
			time.sleep(2)
			# 获取页面源码
			html_page = driver.page_source
			# 利用Beautifulsoup4创建soup对象并进行页面解析
			soup = bs(html_page, "html.parser")
			# 通过soup对象中的findAll函数图像信息提取
			imglist = soup.findAll('img', {'src':re.compile(r'https:.*\.(jpg|png)')})
 
			for imgurl in imglist:  
				if imgurl['src'] not in img_url_dic:
					target = '{}/{}.jpg'.format(picpath, x)
					img_url_dic[imgurl['src']] = '' 
					urllib.request.urlretrieve(imgurl['src'], target)  
					x += 1  
					
	def run(self):
		print ('\t\t\t**************************************\n\t\t\t**\t\tWelcome to Use Spider\t\t**\n\t\t\t**************************************')  
		driver=self.start_brower()
		self.downloadImg(driver)
		driver.close()
		print("Download has finished.")
 
if __name__ == '__main__':  
	craw = Crawler() 
	craw.run()

通过以上的两段代码,可以去爬取百度以及谷歌的图片,不过爬取谷歌图片的代码仍有些不足之处,比如没有实现点击加载这一步,以及由于谷歌的反爬机制很容易爬了一些图片后便强制停止爬取操作…

猜你喜欢

转载自blog.csdn.net/wobeatit/article/details/79559314
今日推荐