user1207929
user1207929

Reputation: 125

How to execute a javascript in a Python webdriver

Selenium 2 Python webdriver:

I was trying to click on an element which is hidden due to the hover effect and was looking for options to unhide and be able to select the element. To do this, I referred to some examples like below:

In java:

JavascriptExecutor je = (JavascriptExecutor) webDriver();

Another example:

browser.execute_script("document.getElementsByClassName('classname').style.display='block'")

When I ran the above example, I got the following exception:

selenium.common.exceptions.WebDriverException: Message: '' 

I am not sure if I had to include any class for executing the javascript. Please let me know if there is anything iam missing.

Upvotes: 0

Views: 15697

Answers (2)

Mohan krishna Sridhar
Mohan krishna Sridhar

Reputation: 43

I am using below command in python to click on an element which is hidden

element=driver.find_element_by_xpath("//div[2]/div/div[2]/div[1]") 
driver.execute_script("arguments[0].click();", element)

Upvotes: 2

p0deje
p0deje

Reputation: 4053

That is because getElementsByClassName returns array of DOM elements. If you need to access first one change your JS to document.getElementsByClassName('classname')[0].style.display='block'

Upvotes: 3

Related Questions