Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 421
packetie Avatar asked Aug 18 '14 17:08

packetie


1 Answers

execute_script accepts arguments, so you can pass the element:

drv.execute_script('arguments[0].setAttribute("style", "color: yellow; border: 2px solid yellow;")', ele)
like image 126
Richard Avatar answered Sep 26 '22 06:09

Richard