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
returnin your script; otherwise,execute_scriptreturnsNone. - 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_scriptunless 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:
| Action | Example JavaScript | Notes |
|---|---|---|
| Get page title | return document.title | Use return to get value |
| Change background color | document.body.style.backgroundColor = 'red' | No return needed for actions |
| Pass arguments | return arguments[0] + arguments[1] | Pass Python args after script string |
| Scroll page | window.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.