Selenium Python绑定:如何在元素上执行JavaScript?

时间:2014-08-18 17:09:26

标签: javascript python selenium selenium-webdriver

使用python selenium脚本触发selenium服务器运行JavaScript代码。它工作正常。

drv.execute_script('<some js code>')

但是,我无法弄清楚如何在使用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?

如果我在浏览器的开发者控制台上,我可以将其作为

运行
ele = $x('//button[@id="xyzw"]')[0]
ele.setAttribute("style", "color: yellow; border: 2px solid yellow;")

不知道如何在python selenium脚本中执行此操作。 提前致谢。

2 个答案:

答案 0 :(得分:9)

execute_script接受参数,因此您可以传递元素:

drv.execute_script('arguments[0].setAttribute("style", "color: yellow; border: 2px solid yellow;")', ele)

答案 1 :(得分:1)

感谢@Richard的回答,他带领我走向了正确的方向,并且Brian的链接(甚至认为是java的帮助)帮助我找出了&#34;的论点&#34 34 ;.

以下代码将满足我的需求。

ele = get_element_by_xpath('//button[@id="xyzw"]');
drv.execute_script('arguments[0].setAttribute("style", "color: yellow; border: 2px solid yellow;")', ele)