文章目錄
前言
作為一名CVer,數據集獲取少不了用到數據、圖片爬蟲技術,谷歌作為全球最大的數據搜索網站,如何從中快速獲取大量有用圖片數據尤為重要,但是技術更新,很多代碼大多就會失效,爬與反爬永遠斗智斗勇...
提示:以下是本篇文章正文內容,下面案例可供參考
一、環境配置
1.安裝selenium
selenium是一個自動化測試工具,能夠模擬瀏覽器行為,在爬蟲上得到了廣泛引用。如果你沒有安裝,請pip install
pip install selenium
2.使用正確的谷歌瀏覽器驅動
下載符合你的谷歌瀏覽器的驅動,chromedriver的版本一定要與Chrome的版本一致,不然就不起作用。
查看自己谷歌瀏覽器的版本,我這里是92.0.4515.131

找到對應的ChromeDriver版本,然后可以從下面的網站下載。
下載地址:https://npm.taobao.org/mirrors/chromedriver/
完整的代碼包以及chromedriver已上傳資源:https://download.csdn.net/download/m0_49688739/21005123
二、使用步驟
1.加載chromedriver.exe
修改以下代碼中的路徑,使用你自己的:
driver = webdriver.Chrome('E:/anaconda/chromedriver.exe', options=ch_op)
2.設置是否開啟可視化界面
selenium模擬瀏覽器行為,其實相當於將我們手動搜索,輸入,點擊等操作用代碼完成,這里可以設置是否開啟可視化界面。
開啟:可以看到瀏覽器自動打開並輸入關鍵詞搜索,滑動頁面等過程,可以監測下載過程。
關閉:不開啟瀏覽器界面,后台運行下載。
默認為關閉,如果需要開啟請注釋掉那兩行代碼
1 # 創建一個參數對象,用來控制chrome是否以無界面模式打開 2 ch_op = Options() 3 # 設置谷歌瀏覽器的頁面無可視化,如果需要可視化請注釋這兩行代碼 4 ch_op.add_argument('--headless') 5 ch_op.add_argument('--disable-gpu')
3.輸入關鍵詞、下載圖片數、圖片保存路徑
這里的圖片保存路徑需要使用\\區分

之后就是獲取圖片url的過程,由於谷歌圖片頁面是動態加載的,獲取每個圖片的原圖就需要點開大圖,並等它加載一會才能獲取到原圖的url,如果時間太短,獲取到的就會是縮略圖,或者出錯。
如果你的網絡狀況不好,請適當延長等待時間time.sleep()。
1 image = driver.find_element_by_xpath('//*[@id="islrg"]/div[1]/div[' + str(i) + ']/a[1]/div[1]/img') 2 3 # 此選項為下載縮略圖 4 # image_src = image.get_attribute("src") 5 image.click() # 點開大圖 6 time.sleep(4) # 因為谷歌頁面是動態加載的,需要給予頁面加載時間,否則無法獲取原圖url,如果你的網絡狀況一般請適當延長 7 # 獲取原圖的url 8 image_real = driver.find_element_by_xpath('//*[@id="Sva75c"]/div/div/div[3]/div[2]/c-wiz/div/div[1]/div[1]/div[2]/div[1]/a/img') 9 image_url = image_real.get_attribute("src")
三、爬取效果
由於需要等待頁面加載,所以爬取時間會比較長,請耐心等待。


下載的基本都是原圖,除非獲取原圖url失敗。
四、完整代碼
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time
import os
import urllib.request
import uuid
def download_pic(url, name, path):
if not os.path.exists(path):
os.makedirs(path)
res = urllib.request.urlopen(url, timeout=3).read()
with open(path + name +'.jpg', 'wb') as file:
file.write(res)
file.close()
def get_image_url(num, key_word):
box = driver.find_element_by_xpath('/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input')
box.send_keys(key_word)
box.send_keys(Keys.ENTER)
box = driver.find_element_by_xpath('//*[@id="hdtb-msb"]/div[1]/div/div[2]/a').click()
# 滾動頁面
last_height = driver.execute_script('return document.body.scrollHeight')
while True:
driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')
time.sleep(2)
new_height = driver.execute_script('return document.body.scrollHeight')
try:
driver.find_elements_by_xpath('//*[@id="islmp"]/div/div/div/div/div[5]/input').click()
except:
pass
if new_height == last_height:
# 點擊顯示更多結果
try:
box = driver.find_element_by_xpath('//*[@id="islmp"]/div/div/div/div[1]/div[2]/div[2]/input').click()
except:
break
last_height = new_height
image_urls = []
for i in range(1, num):
try:
image = driver.find_element_by_xpath('//*[@id="islrg"]/div[1]/div[' + str(i) + ']/a[1]/div[1]/img')
# 此選項為下載縮略圖
# image_src = image.get_attribute("src")
image.click() # 點開大圖
time.sleep(4) # 因為谷歌頁面是動態加載的,需要給予頁面加載時間,否則無法獲取原圖url,如果你的網絡狀況一般請適當延長
# 獲取原圖的url
image_real = driver.find_element_by_xpath('//*[@id="Sva75c"]/div/div/div[3]/div[2]/c-wiz/div/div[1]/div[1]/div[2]/div[1]/a/img')
image_url = image_real.get_attribute("src")
image_urls.append(image_url)
print(str(i) + ': ' + image_url)
except:
print(str(i) + ': error')
pass
return image_urls
if __name__ == '__main__':
# 創建一個參數對象,用來控制chrome是否以無界面模式打開
ch_op = Options()
# 設置谷歌瀏覽器的頁面無可視化,如果需要可視化請注釋這兩行代碼
ch_op.add_argument('--headless')
ch_op.add_argument('--disable-gpu')
url = "https://www.google.com/"
driver = webdriver.Chrome('E:/anaconda/chromedriver.exe', options=ch_op)
driver.get(url)
key_word = input('請輸入關鍵詞:')
num = int(input('請輸入需要下載的圖片數:'))
_path = input('請輸入圖片保存路徑,例如G:\\\\google\\\\images\\\\ :')
# path = "G:\\google\\images_download\\" + key_word + "\\" # 圖片保存路徑改為自己的路徑
path = _path + key_word + "\\"
print('正在獲取圖片url...')
image_urls = get_image_url(num, key_word)
for index, url in enumerate(image_urls):
try:
print('第' + str(index) + '張圖片開始下載...')
download_pic(url, str(uuid.uuid1()), path)
except Exception as e:
print(e)
print('第' + str(index) + '張圖片下載失敗')
continue
driver.quit()
