Home >Backend Development >Python Tutorial >How to Execute JavaScript Code in Selenium Using Python?

How to Execute JavaScript Code in Selenium Using Python?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 18:15:29927browse

How to Execute JavaScript Code in Selenium Using Python?

Executing JavaScript Using Selenium in Python

In the provided code snippet, the goal is to execute a specific JavaScript snippet using Selenium in Python. The code snippet aims to automate a workflow by interacting with a web application. However, the attempt to execute JavaScript using selenium.GetEval fails with an AttributeError.

Solution:

The correct method to execute JavaScript in Selenium using Python is browser.execute_script(). To fix the issue, replace selenium.GetEval() with browser.execute_script().

Revised Code:

<code class="python"># Import necessary modules
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

# Get user inputs
patch = input("Enter patch number\n")
rel = input("Enter release\n")
plat = input("Enter port\n")

# Launch Firefox browser
browser = webdriver.Firefox()

# Navigate to the target web page
browser.get("xxxxxxxxxxxxxxxxx")

# Find and populate various input fields
pdtfamily = browser.find_element_by_id("prodFamilyID")
pdtfamily.send_keys("Database & Tools" + Keys.TAB)
time.sleep(5)

pdt = browser.find_element_by_id("productID")
pdt.send_keys("Intelligent Agent" + Keys.TAB)
time.sleep(5)

pdt1 = browser.find_element_by_id("patchCacheChkBxID")
pdt1.send_keys(Keys.SPACE)
time.sleep(5)

pdt7 = browser.find_element_by_id("M__Idf")
pdt7.send_keys(plat)

pdt8 = browser.find_element_by_id("M__Idg")
pdt8.send_keys("American English")

# Execute the desired JavaScript code
browser.execute_script("submitForm('patchCacheAdd',1,{'event':'ok'});return false;")

# Close the browser
browser.close()</code>

By using browser.execute_script(), the JavaScript code "submitForm('patchCacheAdd',1,{'event':'ok'});return false;" can be executed successfully within the Selenium script written in Python.

The above is the detailed content of How to Execute JavaScript Code in Selenium Using Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn