2

If I want to scroll to the end of a page I use the following:

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

What's the equivalent for scrolling all the way to the right? My first guess was:

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

However, this didn't work and gave the following error:

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

I only want the so-called golf green (the green circle on the right)

2
  • What browser are you using? Commented Apr 4, 2022 at 19:57
  • I am using Chrome Commented Apr 4, 2022 at 20:35

1 Answer 1

1

Instead of directional scrolling an easier approach would be to identify the desired element inducing WebDriverWait for the visibility_of_element_located() and invoke scrollIntoView() as follows:

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

Note : You have to add the following imports :

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 Scrolling to top of the page in Python using Selenium


Update

To scrollIntoView the golf green (the green circle on the right) you can use the following solution:

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")

Saved Screenshot:

green_circle_on_the_right.png

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the tip. The problem is that the element is huge and already in my viewport. So, running your code doesn't make the driver scroll to the right.
IMO, even scrolling and similtaneous screenshot even won't get you the whole picture. You have to adjust shooting strategy.
Yes, I know, so I only want the so-called golf green (the green circle on the right)
Checkout the updated answer and let me know the status.
@HJA24 Approved your edit to hide the actual URL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.