About this lesson
Run JavaScript from Selenium Python: execute_script and the value it returns
Selenium Python AssignmentsAdvancedJavaScript
How it works
driver.execute_script sends a snippet of JavaScript to the browser and runs it inside the current page. The code runs as the body of a function. Without a return, the call gives back None, even when the last expression had a value. A bare document.title gave me None. Add return and the result comes back.
Selenium converts JavaScript values into Python ones. Strings arrive as str, whole numbers as int, decimals as float, true and false as bool, null as None, objects as dicts, arrays as lists and DOM elements as WebElement.
The snippet is a Python string, so mix quote styles to avoid escapes: double quotes outside, single quotes inside. Script errors surface as JavascriptException, carrying the browser's own wording.
About the assignment
You ask the page itself for two things without locator calls: the document title and the content of a pre-filled field.
What you will do
- Run a script that returns the page title and keep the result in a variable.
- Run a second script that finds the pre-filled field by its id in the DOM and returns its
value. - Both results are strings, so join each to its label with
+. - Print the title line first and the value line second.
Common mistakes
Leaving out return
The script runs, yet Python gets
None, and joining that to a label raisesTypeError.Reading a property of a missing node
A wrong id makes
getElementByIdreturnnull, and reading.valuefrom it raisesJavascriptException: "Cannot read properties of null (reading 'value')".Using execute_script when a Selenium call exists
Both values have normal Selenium reads, such as the
driver.titleattribute. Keep script for things Selenium cannot reach.
In a real test suite
Teams wrap small execute_script calls in named helper functions, such as one that reads localStorage for a pytest assertion, so tests stay readable.
The next lesson passes an element into a script and uses it to scroll.
Related lessons
- Open Chrome and Read the Page TitleThe standard way to read the title, which you can compare with the JavaScript way.
- Scroll an Element into ViewPass a found element into
execute_scriptas an argument. - Read an AttributeRead an attribute with Selenium instead of with script code.
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")
# Read the title and the prefilled value with execute_script
finally:
driver.quit()