如何在 Python webdriver 中执行 javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9303024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:13:02  来源:igfitidea点击:

How to execute a javascript in a Python webdriver

javascriptpythonseleniumwebdriver

提问by user1207929

Selenium 2 Python webdriver:

Selenium 2 Python 网络驱动程序:

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:

在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.

我不确定是否必须包含任何类来执行 javascript。如果有什么遗漏,请告诉我。

回答by p0deje

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

那是因为getElementsByClassName返回 DOM 元素数组。如果您需要访问第一个,请将您的 JS 更改为document.getElementsByClassName('classname')[0].style.display='block'

回答by Mohan krishna Sridhar

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

我在 python 中使用下面的命令来点击一个隐藏的元素

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