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

Selenium Python bindings: how to execute JavaScript on an element?

本文关键字:元素 执行 JavaScript Python 绑定 Selenium      更新时间:2023-09-26

使用python selenium脚本触发selenium server运行JavaScript代码。

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

然而,我无法弄清楚如何在使用get_element_by_*() api检索的元素上运行javascript代码。例如,I

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脚本中做它。提前感谢。

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

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

感谢@Richard的回答,他给我指明了正确的方向,以及Brian的链接(甚至认为这是java的),他帮助我弄清楚了"arguments"的含义。

下面的代码可以满足我的需求。

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