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

Used python selenium script to start selenium server to run JavaScript code. It works great.

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

However, I cannot figure out how to run javascript code for an element that was obtained 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 the browser developer console, 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 this in python selenium script. Thanks in advance.

+5
source share
2 answers

execute_script takes arguments, so you can pass an element:

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

Thanks to @ Richard's answer, which led me in the right direction and Brian's link (even thought about it for java), who helped me sort 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
source

Source: https://habr.com/ru/post/1200612/


All Articles