반응형
지금부터 selenium을 이용한 구글 이미지 크롤링하는 방법을 알아보도록 하겠습니다.
selenium이란?
웹 애플리케이션 자동화 및 테스트를 위한 포터블 프레임워크
Selenium 3.0 => Selenium 4.0
1. 환경 설정.
가상 환경 설정
selenium 설치
chromedriver 설치(chromedriver 다운로드(x) → webdriver_manager 설치 후 코드 작성)
a. 가상 환경 설정.
(command 창에 다음과 같이 입력)
python -m venv selenium
cd script
activate
b. selenium 설치
(command 창에 다음과 같이 입력)
pip install selenium
c. webdrive_manager 설치
(command 창에 다음과 같이 입력)
pip install webdriver_manager
2. 본격 코드 작성.
# 다음과 같은 모듈을 import 한다
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
import urllib.request
chrome_options = Options()
service = Service(executable_path=ChromeDriverManager().install())
# 브라우저 꺼짐 방지
chrome_options.add_experimental_option("detach", True)
# 불필요한 에러 메시지 없애기
chrome_options.add_experimental_option("excludeSwitches", ["enable-logging"])
#크롬 드라이버 설정
driver = webdriver.Chrome(service=service, options=chrome_options)
# 웹페이지 해당 주소 이동
driver.get("https://www.google.co.kr/imghp?hl=ko&tab=ri&authuser=0&ogbl")
# 검색창으로 이동하여 아이유를 쓰고 클릭하기
elem = driver.find_element(By.CLASS_NAME, "gLFyf")
elem.send_keys("아이유")
elem.send_keys(Keys.RETURN)
# 많은 이미지를 구하기 위해 스크롤 내리기
SCROLL_PAUSE_TIME = 1
# 스크롤 높이 재기
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
# 스크롤 아래로 내리기
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# 새로운 페이지가 load되기를 기다리기
time.sleep(SCROLL_PAUSE_TIME)
# 새로운 스크롤 높이 구하여 이전 스크롤 높이와 비교하기
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
try:
driver.find_element_by_css_selector(".mye4qd").click()
except:
break
last_height = new_height
# 이미지를 클릭하여 해당 이미지를 다운로드하기
images = driver.find_elements(By.CLASS_NAME, "rg_i.Q4LuWd")
count = 1
for image in images[:100]:
try:
image.click()
time.sleep(2)
imgUrl = driver.find_element(By.CLASS_NAME, "n3VNCb.KAlRDb").get_attribute("src")
urllib.request.urlretrieve(imgUrl, str(count) + ".jpg")
count = count + 1
except:
pass
driver.close()
위 코드를 실행하면 다음과 같이 이미지를 크롤링 할 수 있습니다.
결과 영상)
반응형
'Python 기본 문법' 카테고리의 다른 글
코사인 유사도를 이용한 챗봇 만들기 기본 원리 (0) | 2023.03.16 |
---|---|
시험 대상자 무작위 배정하기(random, shuffle 이용) (0) | 2022.08.08 |
\n 사용, 문자열 한 줄 아래로 출력! (0) | 2022.01.28 |
[파이썬] 구구단 계산기 프로그래밍 (0) | 2021.12.08 |
리스트 자료형, 인덱싱, 슬라이싱 (0) | 2021.12.07 |