首页 > 解决方案 > 如何使用 selenium 向下滚动屏幕?

问题描述

我正在尝试用硒滚动我的屏幕以捕捉一些元素,但我不能这样做......

我用这个:

等待 driver.executeScript("window.scrollBy(0,450)", "");

和这个:

常量页面 = 等待 seleniumUtils.getElementByCSS('body'); 等待 seleniumUtils.click(page); 等待 page.sendKeys(Key.COMMAND,Key.DOWN);

没有任何效果!我需要帮助,请:)

标签: javascriptseleniumautomationui-automationqa

解决方案


只是一个 python 解决方案,用于滚动无限滚动网站。

随意编辑/重写以供您使用...

第 1 步:创建“滚动”功能

def scroll(driver, timeout):
    scroll_pause_time = timeout

    # 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:
            # If heights are the same it will exit the function
            break
        last_height = new_height

第 2 步:创建“滚动”功能后,您可以通过以下方式使用它:

from selenium import webdriver

driver = webdriver.Firefox() # create driver
driver.get('www.yoururl.com') # navigate url
scroll(driver, 5) # use scroll function to scroll the page every 5 second (usefull for infinite scrolling websites)

推荐阅读