Selenium Python 绑定:如何在元素上执行 JavaScript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25368547/
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
Selenium Python bindings: how to execute JavaScript on an element?
提问by packetie
Have used python selenium script to trigger selenium server to run JavaScript code. It works fine.
已使用 python selenium 脚本触发 selenium 服务器运行 JavaScript 代码。它工作正常。
drv.execute_script('<some js code>')
However, I can't figure out how to run javascript code on an element that was retrieved using get_element_by_*() api. For example, I
但是,我不知道如何在使用 get_element_by_*() api 检索的元素上运行 javascript 代码。例如,我
ele = get_element_by_xpath('//button[@id="xyzw"]');
#question: how do I change the "style" attribute of the button element?
If I were on developer console of the browser, I can run it as
如果我在浏览器的开发者控制台上,我可以将它作为
ele = $x('//button[@id="xyzw"]')[0]
ele.setAttribute("style", "color: yellow; border: 2px solid yellow;")
Just don't know how to do it in python selenium script. Thanks in advance.
只是不知道如何在 python selenium 脚本中做到这一点。提前致谢。
回答by Richard
execute_script
accepts arguments, so you can pass the element:
execute_script
接受参数,因此您可以传递元素:
drv.execute_script('arguments[0].setAttribute("style", "color: yellow; border: 2px solid yellow;")', ele)
回答by packetie
Thanks to the answer by @Richard who led me in the right direction and Brian's link (even thought it's for java) who helped me to figure out the meaning of "arguments".
感谢@Richard 的回答,他将我引向了正确的方向,而 Brian 的链接(甚至认为它是针对 Java 的)帮助我弄清楚“参数”的含义。
The following code will do what I need.
下面的代码将做我需要的。
ele = get_element_by_xpath('//button[@id="xyzw"]');
drv.execute_script('arguments[0].setAttribute("style", "color: yellow; border: 2px solid yellow;")', ele)