简体   繁体   中英

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.

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'

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM