Sometimes, normal commands can't do everything on a webpage. JavaScript executor lets you run JavaScript code directly in the browser to control or check things.
0
0
JavaScript executor basics in Selenium Python
Introduction
When a button or element is hidden and normal click doesn't work.
To scroll the page to a specific position quickly.
To get or set values that are not accessible by usual methods.
To run custom JavaScript code for testing special page behaviors.
When you want to check or change styles or attributes dynamically.
Syntax
Selenium Python
driver.execute_script("JavaScript code here")You use execute_script method of the Selenium WebDriver.
The JavaScript code is a string inside the parentheses and quotes.
Examples
This runs a JavaScript alert popup in the browser.
Selenium Python
driver.execute_script("alert('Hello from Selenium!')")This scrolls the page to the bottom.
Selenium Python
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")This gets the page title using JavaScript and stores it in
value.Selenium Python
value = driver.execute_script("return document.title;")Sample Program
This script opens a webpage, scrolls to the bottom, prints the page title using JavaScript, changes the background color, and then closes the browser.
Selenium Python
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By import time # Setup Chrome driver (adjust path as needed) service = Service('/path/to/chromedriver') driver = webdriver.Chrome(service=service) try: driver.get('https://example.com') # Scroll to bottom using JavaScript executor driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(2) # wait to see the scroll effect # 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';") time.sleep(2) # wait to see the color change finally: driver.quit()
OutputSuccess
Important Notes
Always quit the driver to close the browser after tests.
Use return in JavaScript to get values back into Python.
JavaScript executor can run any JavaScript code, so be careful with syntax.
Summary
JavaScript executor runs JavaScript code inside the browser from Selenium.
It helps when normal Selenium commands can't interact with elements properly.
Use execute_script method with JavaScript code as a string.