爬蟲實戰 谷歌圖片爬取 高清圖片

目標

date:2020.5.25
author:pmy
aim:爬取google圖片,關鍵詞cat,兩百張高清圖(非縮略圖)
現階段:能夠實現目標。在之前爬取谷歌圖片的基礎上(縮略圖),這次進行了改進,爬取高清大圖。
存在問題:爬取的效率不高,時間較長,只能完成數量,不能保證所見爲所爬。等待之後學習改進

完整代碼

# date:2020.5.25
# author:pmy
# aim:爬取google圖片
#問題在於,不能保證所爬爲所見

from selenium import webdriver
import time
import os
import requests

# 修改keyword便可以修改搜索關鍵詞 建議也修改存儲目錄
keyword = 'cat'
url = 'https://www.google.com.hk/search?q=' + keyword + '&source=lnms&tbm=isch'


class Crawler_google_images:
    # 初始化
    def __init__(self):
        self.url = url

    # 獲得Chrome驅動,並訪問url
    def init_browser(self):
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument("--disable-infobars")
        browser = webdriver.Chrome(chrome_options=chrome_options)
        # 訪問url
        browser.get(self.url)
        # 最大化窗口,之後需要爬取窗口中所見的所有圖片
        browser.maximize_window()
        return browser

    # 下載圖片
    def download_images(self, browser, num=100):
        #存儲路徑
        picpath = './cat'
        # 路徑不存在時創建一個
        if not os.path.exists(picpath): os.makedirs(picpath)

        count = 0  # 圖片序號
        pos = 0
        # print(num)

        while (True):
            try:
                # 向下滑動
                js = 'var q=document.documentElement.scrollTop=' + str(pos)
                pos += 500
                browser.execute_script(js)
                time.sleep(1)
                # 找到圖片
                # html = browser.page_source#也可以抓取當前頁面的html文本,然後用beautifulsoup來抓取
                # 直接通過tag_name來抓取是最簡單的,比較方便
                img_elements = browser.find_elements_by_xpath('//a[@class="wXeWr islib nfEiy mM5pbd"]')
                try:
                    for img_element in img_elements:
                        #點開大圖頁面
                        img_element.click()
                        time.sleep(0.5)
                        try:
                            # 這裏balabala裏面有好幾個,所以要過濾一下
                            # 取名好煩哦···
                            balabalas = browser.find_elements_by_xpath('//img[@class="n3VNCb"]')

                            if (balabalas):
                                for balabala in balabalas:
                                    src = balabala.get_attribute('src')
                                    #過濾掉縮略圖和無關干擾信息
                                    if src.startswith('http') and not src.startswith(
                                            'https://encrypted-tbn0.gstatic.com'):
                                        print('Found' + str(count) + 'st image url')
                                        # img_url_dic.append(src)
                                        self.save_img(count, src, picpath)
                                        count += 1
                                        #爬取到指定數量圖片後退出
                                        if (count >= num):
                                            return "stop"
                        except:
                            print('獲取圖片失敗')

                    #回退
                    browser.back()
                    time.sleep(0.3)
                except:
                    print('獲取頁面失敗')
            except:
                print("劃不動了")

    def save_img(self, count, img_src, picpath):
        filename = picpath + '/' + str(count) + '.jpg'
        r = requests.get(img_src)
        with open(filename, 'wb') as f:
            f.write(r.content)
        f.close()

    def run(self):
        self.__init__()
        browser = self.init_browser()
        self.download_images(browser, 100)  # 可以修改爬取的圖片數
        browser.close()
        print("############爬取完成")


if __name__ == '__main__':
    craw = Crawler_google_images()
    craw.run()

爬取效果

在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章