Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running javascript in Selenium using Python

I am totally new to Selenium. I want to execute a javascript snippet in the following code(as commented in the code), but can't do so. Please help.

from selenium import webdriver import selenium from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.keys import Keys import time  patch = raw_input("Enter patch number\n") rel = raw_input("Enter release\n") plat = raw_input("Enter port\n")  browser = webdriver.Firefox()  browser.get("xxxxxxxxxxxxxxxxx")  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")  # Here I want to execute this javascript - "submitForm('patchCacheAdd',1,{'event':'ok'});return false"  browser.close() 

If I use -

selenium.GetEval("submitForm('patchCacheAdd',1,{'event':'ok'});return false") 

it errors out as -

AttributeError: 'module' object has no attribute 'GetEval'I  
like image 631
theharshest Avatar asked Oct 17 '11 12:10

theharshest


People also ask

Can Selenium execute JavaScript?

Selenium webdriver can execute Javascript. After loading a page, you can execute any javascript you want. A webdriver must be installed for selenium to work. All it takes to execute Javascript is calling the method execute_script(js) where js is your javascript code.

Can you execute JavaScript in Python?

There are no inbuilt functions available in Python to execute a JavaScript function. Hence you need to install the libraries js2py or requests-html to execute JavaScript from Python.

Can Selenium scrape JavaScript?

One of the benefits of Selenium is that it can web-scrape dynamic JavaScript pages where there are dynamic interactions such as hovering over menu items.

Is JavaScript needed for Selenium?

JavaScript is a programming language that interacts with HTML in a browser, and to use this function in Selenium, JavascriptExecutor is required.


1 Answers

Try browser.execute_script instead of selenium.GetEval.

See this answer for example.

like image 153
Petr Viktorin Avatar answered Sep 30 '22 05:09

Petr Viktorin