在 Selenium 中进行滚动的各种方法

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

搜索了一下,发现有很多文章在介绍如何在 Selenium 中实现滚动。

我也在 Instagram 上发布过,但为了引入更多文章流量,单独写下这篇。

如果有需要更多的滚动方法,我会添加。

通常在 Selenium 中的滚动是通过 JavaScript 实现的。

1. 滚动到所需高度 Y

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

2. 一次滚动到文档底部

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

3. 滚动到文档的最底端

SCROLL_PAUSE_TIME = 0.5

# 获取滚动高度
last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    # 滚动到底部
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    # 等待页面加载
    time.sleep(SCROLL_PAUSE_TIME)

    # 计算新的滚动高度并与上次的滚动高度比较
    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. 如果需要添加

如果有想要的滚动方式,请在评论中留言。

我会尝试实现。

댓글을 불러오는 중...