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
- Find the field and keep the element in a variable.
- Call
execute_scriptwith a short scroll snippet and pass the element as the second argument. - Ask the element if it is displayed. The answer is a
bool, so wrap it instr(). - Print the first line, then read the
valueattribute and print it on a second line.
Common mistakes
Joining a bool to a string
A label plus
is_displayed()raises aTypeErrorabout concatenatingstrandbool. Wrap the call instr().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
Trueeven 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.
Related lessons
- Read a Value with JavaScriptThe first lesson on
execute_scriptand the values it returns. - Click a Button through execute_scriptUse the same element argument to click.
- Check Whether an Element Is DisplayedStudy what
is_displayedreally reports.
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.
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()