Various Ways to Scroll in Selenium

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

I found many articles on how to scroll using Selenium through Google searches.

Although I have posted about it on Instagram, I'm writing it separately to increase the reach of other posts.

I will add more scrolling methods if needed.

Generally, scrolling in Selenium is implemented using JavaScript.

1. Scroll to the desired height Y

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

2. Scroll once to the end of the document

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

3. Scroll to the very end of the document

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. Scrolling using the Page Down key

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

5. Scroll to bring the desired element to the center

driver.execute_script("arguments[0].scrollIntoView({block : 'center'});", desired_element)

6. If there's anything to add

If there is a scroll method you want, please leave a comment.

I will try to implement it.

댓글을 불러오는 중...