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

pac*_*tie 7 javascript python selenium selenium-webdriver

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

drv.execute_script('<some js code>')
Run Code Online (Sandbox Code Playgroud)

但是,我无法弄清楚如何在使用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?
Run Code Online (Sandbox Code Playgroud)

如果我在浏览器的开发者控制台上,我可以运行它

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

只是不知道如何在python selenium脚本中做到这一点.提前致谢.

Ric*_*ard 10

execute_script 接受参数,所以你可以传递元素:

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