PYTHON

파이썬 셀레니움 이미지 크롤링 – 조코딩

# 파이썬 셀레니움 이미지 크롤링으로 배우는 업무 자동화의 기초 (youtube.com)
https://www.youtube.com/watch?v=1b7pXC1-IbE

 

# 소스 코드 (github.com)
https://github.com/youtube-jocoding/python-selenium-google-image-crawling/blob/master/google.py

 

  1. Selenium 설치 및 브라우저 세팅
  2. 구글 이미지 크롤링 코드 작성
  3. 셀레니움 네이버 실시간 검색어 크롤링 방법 소개

 


 

 1. 파이썬 가상 환경 세팅

 

1. 구글에서 검색 : python venv 가상 환경

https://docs.python.org/ko/3/library/venv.html

 

2. 터미널을 열고 실행

python -m venv selenium  // selenium 이라는 이름의 가상 환경을 만듦

cd selenium\Scripts

activate  // 경로 앞에 (selenium) 이 붙었으면 가상환경에 들어왔다는 뜻이다.

pip install selenium  // selenium 설치

 

3. 구글에서 검색 : chromedriver

https://chromedriver.chromium.org/downloads

// 크롬 버전에 맞는 chromedriver 다운로드 (윈도우용 : chromedriver_win32.zip)

// chromedriver.exe 파일을 selenium 폴더에 붙여넣기

 

4. selenium 폴더에 google.py 파일을 생성

 

5. 구글에서 검색 : python selenium example

https://selenium-python.readthedocs.io/getting-started.html

 

 


 

 

 

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

driver = webdriver.Chrome()
driver.get("https://www.google.co.kr/imghp?hl=ko&tab=wi&authuser=0&ogbl")
elem = driver.find_element_by_name("q")
elem.send_keys("조코딩")
elem.send_keys(Keys.RETURN)

SCROLL_PAUSE_TIME = 1
# 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:
        try:
            driver.find_element_by_css_selector(".mye4qd").click()
        except:
            break
    last_height = new_height

images = driver.find_elements_by_css_selector(".rg_i.Q4LuWd")
count = 1
for image in images:
    try:
        image.click()
        time.sleep(2)
        imgUrl = driver.find_element_by_xpath('/html/body/div[2]/c-wiz/div[3]/div[2]/div[3]/div/div/div[3]/div[2]/c-wiz/div[1]/div[1]/div/div[2]/a/img').get_attribute("src")
        opener=urllib.request.build_opener()
        opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]
        urllib.request.install_opener(opener)
        urllib.request.urlretrieve(imgUrl, str(count) + ".jpg")
        count = count + 1
    except:
        pass

driver.close()

 

 

 

Related posts

Leave a Comment