【问题标题】:Selenium Python bindings: how to execute JavaScript on an element?Selenium Python 绑定:如何在元素上执行 JavaScript?
【发布时间】:2014-10-11 16:13:18
【问题描述】:

已使用 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 脚本中执行此操作。 提前致谢。

【问题讨论】:

  • 看看Selenium中的JavascriptExecutor接口。
  • 感谢@Brian 提供链接。它用于 java 绑定,但是,它让我理解了工作解决方案中的“参数”“...arguments[0].setAttribute(....)”的含义。 javascript使用它来引用函数参数(尤其是当函数的参数数量可变时)。
  • 完全没问题。我喜欢分享知识。

标签: javascript python selenium selenium-webdriver


【解决方案1】:

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

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

【讨论】:

  • 感谢您的快速回复。我试过 drv.execute_script(arguments[0].setAttribute("style", "color: yellow; border: 2px solid yellow;"), ele);但出现错误:未定义名称“参数”。知道为什么吗?
  • 原来我错过了单引号,以下工作正常:drv.execute_script('arguments[0].setAttribute("style", "color: yellow; border: 2px solid yellow;") ', ele) 嗨@Richard,您能再次更新您的答案以便我接受吗?
  • @codingFun 我觉得我只是让您了解了其中的一部分,您是接受我语法错误答案并找出正确语法的人。话虽如此,如果你还愿意接受我的回答,那也没关系。
【解决方案2】:

感谢@Richard 的回答,他带领我朝着正确的方向前进,Brian 的链接(甚至认为它是针对 java 的)帮助我弄清楚了“参数”的含义。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 2012-01-05
    • 2017-08-24
    • 1970-01-01
    • 2013-05-20
    • 2013-01-12
    • 2019-01-08
    相关资源
    最近更新 更多