Skip to content
CodeKruPro

Scroll an Element into View

64/80

Scroll an Element into View

scrollIntoView moves the page so the element is in the viewport. The first printed line comes from is_displayed() after the scroll. Also print a value from the page.

Task:

  1. Find #preFilledTextField
  2. Scroll it into view
  3. Print whether it is displayed and print its value

Print the lines below exactly.

Expected output:

Scrolled to element: True
Value: Codekru

About this lesson

Selenium Python scrollIntoView: bring a far-down element into the viewport

Selenium Python AssignmentsAdvancedJavaScript

How it works

The driver has no scroll method. The usual way is to call the browser's own scrollIntoView function through execute_script. You find the element with Selenium and pass it in as an argument, and the script reads it as arguments[0].

is_displayed does not mean "on screen right now". On the Text Fields page the pre-filled field sits well below the first screen, yet the method returned True before any scrolling. It checks that the element is rendered, not where it sits.

To prove a scroll happened, read window.scrollY with a second script. Mine went from 0 to 579. The scroll call itself returns None.

About the assignment

You locate the pre-filled field, scroll it into view, and print two facts: whether Selenium calls it displayed, and what it holds.

What you will do

  1. Find the field and keep the element in a variable.
  2. Call execute_script with a short scroll snippet and pass the element as the second argument.
  3. Ask the element if it is displayed. The answer is a bool, so wrap it in str().
  4. Print the first line, then read the value attribute and print it on a second line.

Common mistakes

  • Joining a bool to a string

    A label plus is_displayed() raises a TypeError about concatenating str and bool. Wrap the call in str().

  • Forgetting to pass the element

    Without the second argument, the browser raises JavascriptException: "Cannot read properties of undefined (reading 'scrollIntoView')".

  • Treating is_displayed as proof of scrolling

    It reports True even far below the fold, so it cannot prove the scroll happened.

In a real test suite

A page object method such as scroll_to(element) often wraps this script, used before screenshots or when a sticky header covers a target. A normal click scrolls for you, so manual scrolling is for special cases.

The next lesson also uses an element argument, but to trigger a click instead of a scroll.

To try one of these calls on any page without a task, open the Online Selenium Python Compiler.

Starter code

The editor above opens with this code. Fill in the TODO lines, then run and submit it.

main.py
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
try:
    driver.get("https://testkru.com/Elements/TextFields")
    # Scroll #preFilledTextField into view and print both lines
finally:
    driver.quit()