🧐 🤔 그거 어떻게 쓰더라 🙄 😙

구글 이미지 검색 결과 크롤링 (selenium)

2022. 7. 19. Evergood Kim이가 씀

참고1: https://velog.io/@jungeun-dev/Python-%EC%9B%B9-%ED%81%AC%EB%A1%A4%EB%A7%81Selenium-%EA%B5%AC%EA%B8%80-%EC%9D%B4%EB%AF%B8%EC%A7%80-%EC%88%98%EC%A7%91
참고2: https://velog.io/@sangyeon217/deprecation-warning-executablepath-has-been-deprecated
참고1이 구버전이 되어서 그런지 안 돼서 참고2 등을 보며 수정했다.

# 구글 이미지 긁어오기

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time
import urllib.request
import os
from  selenium.webdriver.common.by import By


def set_chrome_driver():
    chrome_options = webdriver.ChromeOptions()
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
    return driver


def createDirectory(directory):
    try:
        if not os.path.exists(directory):
            os.makedirs(directory)
    except OSError:
        print("Error: Failed to create the directory.")


def crawling_img(val):
    driver = webdriver.Chrome('./chromedriver')
    driver.get("https://www.google.co.kr/imghp?hl=ko&tab=wi&authuser=0&ogbl")
    driver.execute_script("document.querySelector('input.gLFyf.gsfi').value = '" + val + "'")  # 검색창에 검색어 입력
    driver.execute_script("document.querySelector('form').submit()")  # 검색 요청 (검색 폼 제출)

    # # 스크롤 끝까지 내려 검색결과 더 보기
    # # 테스트를 빨리 하려고 스크롤 안 내린다. 이 부분 주석처리를 풀면 스크롤을 끝까지 내린다.
    # SCROLL_PAUSE_TIME = 1
    # # Get scroll height
    # last_height = driver.execute_script("return document.body.scrollHeight")  # 페이지의 세로길이
    # while True:
    #     driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")  # 브라우저 끝까지 스크롤을 내림
    #     time.sleep(SCROLL_PAUSE_TIME)  # 추가 검색결과가 뜰 동안 기다린다
    #     # 페이지의 세로길이가 기존과 비교해서 더 길어지지 않았으면 추가 검색결과가 없는 것이므로 반복 종료
    #     new_height = driver.execute_script("return document.body.scrollHeight")
    #     if new_height == last_height:
    #         break
    #         # try:
    #         #     driver.find_elements(By.CSS_SELECTOR,'mye4qd')
    #         #     # driver.find_element_by_css_selector(".mye4qd").click()
    #         # except:
    #         #     break
    #     last_height = new_height

    imgs = driver.find_elements(By.CSS_SELECTOR, ".rg_i.Q4LuWd")  # 이미지 요소들 모두 찾기
    dir = "./idols/" + val  # 이미지 저장 경로 (리눅스)
    # dir = ".\idols" + "\\" + val  # 이미지 저장 경로 (윈도우)

    createDirectory(dir)  # 이미지들 저장할 폴더 생성
    count = 1  # 이미지 번호
    for img in imgs:  # 각 이미지 순회
        print(count)
        if count > 5:  # 테스트용으로 이미지 5개만 다운로드 한다. 검색결과 페이지를 모두 긁으려면 이 조건문을 없앤다.
            break
        try:
            img.click()  # 검색결과 이미지를 클릭하여
            time.sleep(1)  # 상세보기가 다운될 동안 대기
            imgUrl  = driver.find_element(By.XPATH,
                '//*[@id="Sva75c"]/div/div/div[3]/div[2]/c-wiz/div/div[1]/div[1]/div[3]/div/a/img').get_attribute(
                "src")  # 구글 이미지검색결과 페이지의 내부구조가 바뀌면 여길 수정해야 한다.
            path = dir + "/"  # 경로 (리눅스)
            # path = dir + "\\"  # 경로 (윈도우)
            urllib.request.urlretrieve(imgUrl, path + val + str(count) + ".jpg")
            count = count + 1
            if count >= 260:
                break
        except Exception as e:
            print(e)
    driver.close()


searchVals = ["병아리", "딸기", "고양이"]  # 검색어 목록

for val in searchVals:  # 각 검색어별로
    crawling_img(val)  # 크롤링
728x90