Backend/Python
[Python] Selenuim 스크롤 조작하기
천우산__
2024. 2. 1. 12:40
Python 으로 크롤링을 진행할 때, 간혹 스크롤의 존재로 인해
원하는 정보 모두를 크롤링 하기 어려울 떄가 있다.
예를 들면, 페이지 첫 화면에서 모든 정보를 랜더링 하지 않고, 스크롤을 아래로 내림으로써 추가적으로 컨텐츠를 불러오는 페이지가 있다.
이 때 전체 페이지 요소를 확인하기 위해서는 스크롤이 더 이상 내려가지 않을 때 까지 내리는 작업이 필요하다.
from selenium import webdriver
browser = webdriver.Chrome()
browser.get(url) # 크롤링 하기 위한 url 입력
# 현재 스크롤 위치를 저장
last_height = browser.execute_script("return Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight );")
while True:
# 페이지 스크롤
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# 새로운 스크롤 높이 가져오기
new_height = browser.execute_script("return Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight );")
# 더 이상 스크롤이 되지 않으면 반복 종료
if new_height == last_height:
break
# 스크롤이 내려가면, 마지막 스크롤 위치를 수정
last_height = new_height
# 이후 페이지 크롤링 진행
스크롤이 더 이상 내려가지 않으면, 더 이상 불러올 컨텐츠가 없다는 의미가 되므로
이후 페이지 크롤링을 진행하면 처음 원했던 것 처럼, 확인한 페이지의 모든 컨텐츠를 대상으로 요소를 확인할 수 있다.