반응형
selenium을 이용해 크롤링하는 법이 궁금하다면 아래의 링크 참고
2021.09.15 - [Python] - [Python]Python selenium을 이용하여 웹에서 이미지 크롤링 후 다운
[Python]Python selenium을 이용하여 웹에서 이미지 크롤링 후 다운
파이썬을 이용하여 이미지 크롤링 후 다운로드하는 것 까지 해보겠다. 프로젝트 진행 전 필요한 개발환경으로는 아래의 3가지가 필요하다. 0. Python 설치 1. VSCode설치 2. Python 가상 환경 설정 3. 크
tae-hui.tistory.com
크롤링을 하다 보면 스크롤을 조정해야 하는 경우가 많다. 이를 쉽고 간편하게 컨트롤 할 수 있는 코드를 설명하겠다.
스크롤을 조정하는 함수 execute_script
- 이제 이 함수를 가지고 어떻게 실제 적용시키는지 알아보겠다.
- 아래의 코드는 구글 이미지에서 강아지를 검색하여 다운로드한 경우이다.
from selenium import webdriver
from selenium.webdriver.common import keys
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time
import urllib.request
import os
site = ('https://www.google.co.kr/search?q=%EA%B0%95%EC%95%84%EC%A7%80&hl=ko&authuser=0&tbm=isch&sxsrf=ALeKk01X3frCHCz7_Eso7u3Hgv2bNL0ucw%3A1622281867628&source=hp&biw=1920&bih=937&ei=iw6yYLCDJLTdmAWHlJugCA&oq=%EA%B0%95%EC%95%84%EC%A7%80&gs_lcp=CgNpbWcQAzIECCMQJzIFCAAQsQMyBQgAELEDMgUIABCxAzIFCAAQsQMyBQgAELEDMgIIADICCAAyAggAMgIIADoHCCMQ6gIQJ1DwCFjIDmCIEGgCcAB4AYABZYgBowWSAQM1LjKYAQCgAQGqAQtnd3Mtd2l6LWltZ7ABCg&sclient=img&ved=0ahUKEwjw9MXzzu7wAhW0LqYKHQfKBoQQ4dUDCAc&uact=5')
driver = webdriver.Chrome()
# 이미지 페이지를 연다
driver.get(site)
last_height = driver.execute_script("return document.body.scrollHeight") #스크롤의 크기를 확인한다.
while True: # Scroll down to bottom
# Wait to load page
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") #스크롤은 맨 아래로 내린다.
# Calculate new scroll height and compare with last scroll height
time.sleep(1)
new_height = driver.execute_script("return document.body.scrollHeight") #다시한번 스크롤의 크기를 확인한다.
print(new_height)
print(last_height)
if new_height == last_height: #처음에 확인한 스크롤의 크기와 맨 아래로 내린 후 확인한 스크롤의 크기르 비교한다.
break
last_height = new_height
# 검색 후 나온 모든 이미지를 images에 넣는다. #여러가지를 찾을때는 elements
driver.find_element_by_xpath("/html/body/div[9]/div/ins").click()
driver.switch_to.window(driver.window_handles[0])
time.sleep(1)
driver.find_element_by_xpath("/html/body/div[6]/div/ins").click()
driver.switch_to.window(driver.window_handles[0])
time.sleep(1)
# Wait to load page
driver.execute_script("window.scrollTo(document.body.scrollHeight, 0);") #스크롤 올리기
# Calculate new scroll height and compare with last scroll height
time.sleep(1)
driver.find_element_by_xpath("/html/body/div[2]/div/ins").click()
driver.switch_to.window(driver.window_handles[0])
간단하게 정리하자면
driver.execute_script("0, window.scrollTo(document.body.scrollHeight);") #스크롤 내리기
driver.execute_script("window.scrollTo(document.body.scrollHeight, 0);") #스크롤 올리기
반응형
'Python' 카테고리의 다른 글
[Python 배열 섞기] random.shuffle 함수 (0) | 2022.08.08 |
---|---|
[Python selenium] 크롤링 시 쉽게 요소 찾는법 (0) | 2022.07.17 |
[Python] try except 문 활용 에러 고치기urllib.error.HTTPError: HTTP Error 429: Too Many Requests (0) | 2022.05.27 |
[Python][datetime] 날짜, 시간 다양한 출력법 정리 (0) | 2022.05.26 |
[Python]Python selenium을 이용하여 웹에서 이미지 크롤링 후 다운 (0) | 2021.09.15 |