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

How to Execute JavaScript in Selenium Python: Simple Guide

In Selenium Python, you can run JavaScript code using the execute_script method of the WebDriver instance. This method lets you execute any JavaScript code on the current page and return results if needed.
๐Ÿ“

Syntax

The execute_script method runs JavaScript code in the browser context. You pass a string with your JavaScript code as the first argument. You can also pass additional arguments that become available inside the script as arguments[0], arguments[1], etc.

The method returns the result of the JavaScript execution, if any.

python
driver.execute_script("return document.title")
๐Ÿ’ป

Example

This example opens a webpage, runs JavaScript to get the page title, and prints it. It also changes the background color of the page using JavaScript.

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')  # Run browser in headless mode
service = Service()
driver = webdriver.Chrome(service=service, options=options)

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

    # Change background color using JavaScript
    driver.execute_script('document.body.style.backgroundColor = "lightblue"')

finally:
    driver.quit()
Output
Page title is: Example Domain
โš ๏ธ

Common Pitfalls

  • Not returning a value: If you want to get a result from JavaScript, use return in your script; otherwise, execute_script returns None.
  • Wrong argument usage: When passing arguments, access them inside JavaScript as arguments[0], arguments[1], etc.
  • Using deprecated methods: Avoid older Selenium methods like execute_async_script unless you need asynchronous JavaScript execution.
python
wrong = driver.execute_script('document.title')  # Missing return, returns None
right = driver.execute_script('return document.title')  # Correct usage
๐Ÿ“Š

Quick Reference

Here is a quick summary of how to use execute_script:

ActionExample JavaScriptNotes
Get page titlereturn document.titleUse return to get value
Change background colordocument.body.style.backgroundColor = 'red'No return needed for actions
Pass argumentsreturn arguments[0] + arguments[1]Pass Python args after script string
Scroll pagewindow.scrollTo(0, document.body.scrollHeight)Scroll to bottom of page
โœ…

Key Takeaways

Use driver.execute_script() to run JavaScript in Selenium Python.
Always use 'return' in your JavaScript to get a result back.
Pass extra arguments after the script string and access them as arguments[n] in JS.
execute_script can run any JavaScript, including DOM changes and page interactions.
Avoid common mistakes like missing return or wrong argument usage.