Coding, Filming, and Nothing
article thumbnail
이미지 데이터 증강을 위해 크롤링을 시도해보려고 했고, 구글링 했을 때 나오는 코드들 중에 일부가 selenium 예전 버전을 활용하고 있어서 최신화, 그리고 내 환경(윈도우)에서 맞게 돌아가게 수정함.
또한, 썸네일 이미지를 가져오는 것이 아니고 이미지 소스의 URL을 먼저 저장후 데이터를 내려 받기 때문에 원본 화질 다운 받도록 코드를 만듬 

 

Requirements

pip install -U selenium

크롬 드라이버 설치

https://chromedriver.chromium.org/downloads 

 

ChromeDriver - WebDriver for Chrome - Downloads

Current Releases If you are using Chrome version 113, please download ChromeDriver 113.0.5672.24 If you are using Chrome version 112, please download ChromeDriver 112.0.5615.49 If you are using Chrome version 111, please download ChromeDriver 111.0.5563.64

chromedriver.chromium.org

 

 

코드

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


chrome_options = webdriver.ChromeOptions()
chrome_options.binary = 'C://chromedriver_win32/chromedriver.exe' # 드라이버 실행파일 경로

query = '춘식이'

driver = webdriver.Chrome()
driver.get(f'https://www.google.com/imghp')
search_bar = driver.find_element(By.NAME,"q")
search_bar.send_keys(query)
search_bar.submit()

PAUSE_TIME = 2
last_hegiht = driver.execute_script("return document.body.scrollHeight")
new_height = 0

while True :
    driver.execute_script("window.scrollBy(0,5000)")
    time.sleep(PAUSE_TIME)
    new_height = driver.execute_script("return document.body.scrollHeight")

    if new_height - last_hegiht > 0 :
        last_hegiht = new_height
        continue
    else :
        break

img_elements = driver.find_elements(By.CSS_SELECTOR,".rg_i")
imgs = []

for idx, img in enumerate(img_elements) :
    print(f"{query} : {idx+1}/{len(img_elements)} proceed...")
    try :
        img.click()
        time.sleep(PAUSE_TIME)
        # 이부분에서 에러나면, 직접 개발자 도구 활용해서 XPATH 추출한 뒤에 변경
        img_element = driver.find_element(By.XPATH,'//*[@id="Sva75c"]/div[2]/div/div[2]/div[2]/div[2]/c-wiz/div/div[2]/div[1]/a/img[1]')
        img_src = img_element.get_attribute('src')
        img_alt = img_element.get_attribute('alt')
        imgs.append({
            'alt' : img_alt,
            'src' : img_src
        })
        
    except :
        print(f'err in {idx}')
        pass

driver.close()

save_path = f'D:\git\crawled\{query}'
import os
if not os.path.exists(save_path):
    os.mkdir(save_path)

total_N = len(imgs)
for idx, one in enumerate(imgs):
    src = one['src']
    alt = one['alt']
    urllib.request.urlretrieve(src,  f"{save_path}\{query}_{idx}.png")
    print(idx, alt)

print('done')

 

  • query에 입력한 검색어로 이미지 크롤링을 하는 코드 
  • 크롬에서 스크롤을 모두 내려 이미지를 전부 로드
  • 하나씩 클릭하면서 CSS 코드 속 이미지 url를 크롤링
  • 가져온 url을 토대로 이미지 원본 다운로드, save_path에 저장

 

주의사항

  • chrome_options.binary 에 본인이 다운받은 크롬 드라이버 실행 경로를 지정해주어야 함 
  • img_element = driver.find_element(By.XPATH, ~) 에서 에러가 난다면 

  • 크롬 - 이미지 - 이미지 클릭 - F12를 통해 개발자도구 열기
  • 그림에 마커된 순서대로 클릭 (3은 오른쪽), XPath 복사
  • 코드의 By.XPATH, 뒤 형식에다가 복사한 내용을 붙여넣기 

 

 

끝.

profile

Coding, Filming, and Nothing

@_안쑤

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!