0
0
Selenium-pythonHow-ToBeginner ยท 4 min read

How to Use execute_script in Selenium for JavaScript Execution

Use Selenium's execute_script method to run JavaScript code directly in the browser during a test. It takes a JavaScript string and optional arguments, allowing you to interact with the page beyond standard Selenium commands.
๐Ÿ“

Syntax

The execute_script method runs JavaScript code in the browser context. It accepts a JavaScript string as the first argument and optional arguments to pass into the script.

  • driver.execute_script(script, *args): Runs the JavaScript script.
  • script: A string containing JavaScript code.
  • *args: Optional arguments passed to the script as arguments[0], arguments[1], etc.
python
result = driver.execute_script('return document.title')
๐Ÿ’ป

Example

This example opens a webpage, uses execute_script to get the page title, and scrolls down the page by 100 pixels.

python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--headless')
service = Service()
driver = webdriver.Chrome(service=service, options=options)

try:
    driver.get('https://example.com')
    # Get page title using execute_script
    title = driver.execute_script('return document.title')
    print(f'Page title is: {title}')

    # Scroll down by 100 pixels
    driver.execute_script('window.scrollBy(0, 100)')
finally:
    driver.quit()
Output
Page title is: Example Domain
โš ๏ธ

Common Pitfalls

  • Not returning a value from the JavaScript code when you expect one. Use return to get a result back.
  • Passing complex Python objects directly as arguments; only simple types like strings, numbers, and WebElements are supported.
  • Using execute_script for actions that Selenium can do natively, which can make tests harder to maintain.
  • Forgetting to handle asynchronous JavaScript; execute_script runs synchronously.
python
wrong = driver.execute_script('document.title')  # returns None
right = driver.execute_script('return document.title')  # returns title string
๐Ÿ“Š

Quick Reference

UsageDescription
driver.execute_script('return document.title')Get the page title
driver.execute_script('window.scrollBy(0, 100)')Scroll down 100 pixels
driver.execute_script('arguments[0].click()', element)Click an element via JS
driver.execute_script('return arguments[0].innerText', element)Get element text
โœ…

Key Takeaways

Use execute_script to run JavaScript code directly in the browser during Selenium tests.
Always use 'return' in your JavaScript if you want to get a value back in Python.
Pass simple arguments like strings, numbers, or WebElements to your script using arguments.
Avoid using execute_script for actions Selenium can do natively to keep tests clear.
execute_script runs synchronously and does not handle asynchronous JavaScript automatically.