Education logo

How to run JavaScript in Selenium Python, pass and get values from it

Selenium is a popular library used for testing interfaces or creating bots for websites. Although most of the functionality is available in Python methods, sometimes we need to execute JavaScript code on a page. In this article, let's see how to do it.

By ITWEBMIND.COMPublished 3 years ago • 3 min read

To run JavaScript within Selenium using Python, you can utilize the execute_script() function. This function enables the execution of JavaScript within the current page's context, as managed by the Selenium WebDriver. Below is a simple example demonstrating its application:

from selenium import webdriver

# Setting up the WebDriver. In this case, ChromeDriver is being used.

driver = webdriver.Chrome('/path/to/chromedriver')

# Navigating to a specific webpage.

driver.get('http://example.com')

# Running a JavaScript command.

driver.execute_script("alert('Hello, World!');")

# Remember to terminate the driver.

driver.quit()

In this instance, the execute_script() function is employed to create a basic JavaScript alert(), however, you can replace the JavaScript string with any script you wish to execute.

Retrieving Data from JavaScript in Python

To fetch data from JavaScript's return output in Selenium with Python, employ the execute_script() function in a similar manner as previously, but this time, capture its return value. The execute_script() function will yield whatever the JavaScript code outputs. Here's a method to do this:

from selenium import webdriver

# Setting up the WebDriver, with ChromeDriver as an example.

driver = webdriver.Chrome('/path/to/chromedriver')

# Accessing a specific webpage.

driver.get('http://example.com')

# Running a JavaScript command and storing its return value.

# For instance, retrieving the webpage's title using JavaScript.

title = driver.execute_script("return document.title;")

# Displaying the result.

print("The title of the page is:", title)

# Remember to terminate the driver.

driver.quit()

This script executes JavaScript return document.title;, which fetches the title of the current webpage. This title is then assigned to the Python variable title and displayed.

You can substitute "return document.title;" with any JavaScript command that yields data, and the function will return that data to your Python script.

Passing Data to JavaScript

To feed arguments to the execute_script() function in Selenium while using Python, you can include them in the function invocation following the JavaScript code line.

These arguments are then accessible within your JavaScript code. In JavaScript, the arguments[index] variable is used to access the provided arguments, where index signifies the argument's index (beginning at 0).

from selenium import webdriver

# Setting up the WebDriver, with ChromeDriver as an example.

driver = webdriver.Chrome('/path/to/chromedriver')

# Navigating to a webpage.

driver.get('http://example.com')

# Defining JavaScript code with arguments

js_code = "return arguments[0] + arguments[1];"

# Providing arguments to execute_script

result = driver.execute_script(js_code, 10, 20)

# Displaying the outcome

print("The result is:", result)

# Closing the driver

driver.quit()

In this example, the JavaScript code return arguments[0] + arguments[1]; is designed to add two numbers. The values 10 and 20 are passed as arguments to execute_script(). The JavaScript then calculates the sum of these numbers, which is stored in the Python variable result and printed.

Alternatively, a variable could be directly embedded into the JS code string, but this approach can sometimes lead to issues with quotes and strings, and hence should be used with caution.

Handling Complex JavaScript Objects

While simple scripts like alerts or returning a page title are straightforward, execute_script() is also capable of handling more complex JavaScript objects. For example, if you need to interact with a JavaScript object that is part of your webpage's structure, execute_script() can be used to retrieve or manipulate these objects. Consider the following:

# Example: Retrieving a complex JavaScript object

complex_object = driver.execute_script("return window.someComplexObject;")

print("Complex Object:", complex_object)

This approach is particularly useful when dealing with single-page applications (SPAs) where much of the data and state are managed within JavaScript objects.

Interacting with Local Storage and Session Storage

Another advanced use of execute_script() involves interaction with the browser's local storage and session storage. This is useful for scenarios where you need to set or get items from the local storage for testing purposes. For example:

# Setting an item in local storage

driver.execute_script("localStorage.setItem('key', 'value');")

# Getting an item from local storage

value = driver.execute_script("return localStorage.getItem('key');")

print("Value from Local Storage:", value)

Executing Asynchronous JavaScript

Selenium’s execute_script() method can also run asynchronous JavaScript. This is crucial when dealing with AJAX calls or any operations that are not immediately completed. You can use JavaScript’s async and await syntax within the execute_script() method to handle these cases.

# Example: Executing asynchronous JavaScript

async_result = driver.execute_script("return new Promise(resolve => setTimeout(() => resolve('Result after 2 seconds'), 2000));")

print("Asynchronous result:", async_result)

Understanding and leveraging the execute_script() method in Selenium with Python opens up a multitude of possibilities for web automation and testing. It allows you to perform actions that are otherwise impossible using standard Selenium APIs. By mastering this tool, you can ensure more robust, comprehensive, and effective automated testing scenarios.

how to

About the Creator

ITWEBMIND.COM

A blog where I write my experience in website development, programming, SEO, design, productivity, Python, JavaScript, PHP, SQL, HTML, CSS, etc — my programming blog, Reddit, Patreon, Medium.

Enjoyed the story? Support the Creator.

Subscribe for free to receive all their stories in your feed.

Subscribe For Free

Reader insights

Comments

There are no comments for this story

Be the first to respond and start the conversation.

Sign in to comment
    Written by ITWEBMIND.COM