最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin8浏览0评论

Have used python selenium script to trigger selenium server to run JavaScript code. It works fine.

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

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.

Have used python selenium script to trigger selenium server to run JavaScript code. It works fine.

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

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.

Share Improve this question edited Aug 2, 2017 at 13:40 Ripon Al Wasim 37.8k42 gold badges159 silver badges178 bronze badges asked Aug 18, 2014 at 17:09 packetiepacketie 5,06912 gold badges40 silver badges79 bronze badges 3
  • Take a look at the JavascriptExecutor interface in Selenium. – Brian Commented Aug 18, 2014 at 17:28
  • Thanks @Brian for the link. It's for java binding, nevertheless, it makes me understand what the "arguments" in the working solution "...arguments[0].setAttribute(....)" means. It's used by javascript to refer to the function parameter (esp when the number of parameters to the function is variable). – packetie Commented Aug 18, 2014 at 17:38
  • No problem at all. I love sharing knowledge. – Brian Commented Aug 18, 2014 at 17:39
Add a ment  | 

2 Answers 2

Reset to default 16

execute_script accepts arguments, so you can pass the element:

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

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".

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)
发布评论

评论列表(0)

  1. 暂无评论