Skip to content
CodeKruPro

Read a Value with JavaScript

63/80

Read a Value with JavaScript

execute_script runs JavaScript in the page and returns the value.

Task:

  1. Read document.title
  2. Read the value of preFilledTextField
  3. Print both

Print the lines below exactly.

Expected output:

JS Title: Text Fields
JS Value: Codekru

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

  1. Run a script that returns the page title and keep the result in a variable.
  2. Run a second script that finds the pre-filled field by its id in the DOM and returns its value.
  3. Both results are strings, so join each to its label with +.
  4. 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 raises TypeError.

  • Reading a property of a missing node

    A wrong id makes getElementById return null, and reading .value from it raises JavascriptException: "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.title attribute. 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.

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")
    # Read the title and the prefilled value with execute_script
finally:
    driver.quit()