如何使用 Selenium 和 Python 向右滚动最远

How to scroll furthest to the right using Selenium and Python

如果我想滚动到页面末尾,我使用以下命令:

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

一直向右滚动相当于什么?我的第一个猜测是:

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

但是,这不起作用并出现以下错误:

JavascriptException}Message: javascript error: Cannot read properties of null (reading 'scrollWidth')

我只想要所谓的高尔夫果岭(右边那个绿色圆圈)

代替定向滚动,一种更简单的方法是识别所需的元素诱导 WebDriverWait for the and invoke ,如下所示:

element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "element_css")))
driver.execute_script("return arguments[0].scrollIntoView(true);", element)

注意:您必须添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

You can find a relevant detailed discussion in


更新

要滚动查看高尔夫果岭(右侧的绿色圆圈)可以使用以下解决方案:

driver.get(URL)
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "svg g path[fill='#92f100']")))
driver.execute_script("return arguments[0].scrollIntoView(true);", element)
driver.save_screenshot("green_circle_on_the_right.png")

保存的屏幕截图: