본문 바로가기

InfoSec Log/Python

[Python] 구글 이미지 웹 스크래핑

"Google 이미지 검색 탭에 특정 키워드를 입력하여 해당 키워드의 결과로 나오는 이미지들을 로컬 컴퓨터의 파일로 저장"

 

 

전체 소스코드

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
import urllib.request

driver = webdriver.Chrome() # 크롬 브라우저 열기
driver.maximize_window() # 창 최대화

url = "https://www.google.com/imghp"
driver.get(url=url) # 구글 이미지 접속
driver.implicitly_wait(time_to_wait=10) # 화면 로드 완료 시까지 최대 10초 휴식

elem = driver.find_element(By.CSS_SELECTOR, '#APjFqb') # 검색창 Selector
elem.send_keys("nature") # 검색어 'nature'
elem.send_keys(Keys.RETURN) # 검색 결과 반환
driver.implicitly_wait(time_to_wait=10)



# 웹 페이지 끝까지 내리기
# 웹 서버 과부하 방지하고자 주석처리
# SCROLL_PAUSE_TIME = 0.5

# # Get scroll height
# last_height = driver.execute_script("return document.body.scrollHeight")

# while True:
#     # Scroll down to bottom
#     driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

#     # Wait to load page
#     time.sleep(SCROLL_PAUSE_TIME)

#     # Calculate new scroll height and compare with last scroll height
#     new_height = driver.execute_script("return document.body.scrollHeight")
#     if new_height == last_height:
#         break
#     else:
#         last_height = new_height



links = []
images = driver.find_elements(By.XPATH, "//div[@class='H8Rx8c']") # 이미지 썸네일
for i in images:
    i.click()
    driver.implicitly_wait(time_to_wait=10)
    image = driver.find_element(By.XPATH, "//div/a[@class='jlTjKd']/img") # 썸네일 누른 후 나오는 이미지
    if image.get_attribute('src') is not None: # 'src' 속성이 존재할 시
        links.append(image.get_attribute('src')) # 리스트에 추가

# print(links)


for i, k in enumerate(links): # 리스트 내 요소의 인덱스 번호 및 값
    url = k
    urllib.request.urlretrieve(url, "./nature_imgs/"+str(i)+".jpg") # 파일로 저장

print("다운로드를 성공적으로 완료하였습니다.")

 

 

Result

/nature_imgs/