셀레니움에서 스크롤을 하는 다양한 방법

힘센캥거루
2023년 5월 26일(수정됨)
7
python

구글링을 하니 셀레니움으로 스크롤을 하는 방법을 찾는 글들이 많았다.

나도 인스타그램 글에 올려 두었으나, 다른 글들의 유입을 위해 따로 글로 써둔다.

혹시나 더 필요한 스크롤 방법이 있다면 추가해보겠다.

일반적으로 셀레니움에서의 스크롤은 자바스크립트를 이용해서 구현한다.

1. 원하는 높이 Y까지 스크롤

driver.execute_script("window.scrollTo(0, Y)")

2. 문서의 끝까지 1회 스크롤

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

3. 문서의 제일 끝까지 스크롤

SCROLL_PAUSE_TIME = 0.5

# 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:
        break
    last_height = new_height

4. Page Down 키를 이용한 스크롤

driver.find_element(By.XPATH, '/html/body').send_keys(Keys.PAGE_DOWN)

5. 내가 원하는 요소가 가운데 오도록 스크롤하기

driver.execute_script("arguments[0].scrollIntoView({block : 'center'});", 원하는 요소)

6. 추가 할 것이 있다면

원하는 스크롤 방식이 있다면 댓글로 달아주길 바란다.

한번 구현해보겠다.

댓글을 불러오는 중...