6

I using Selenium Python bindings to find some elements. in some place i need to use execute_script method. Hot to get returned values from executing this script?

So i put:

browser = driver.Chrome() #for example
script = "document.getElementById('element')"
browser.execute_script(script)

How to receive values into python log or variable from that script? Like element`s ID, text, etc.?

2 Answers 2

4

I had a problem where selenium was not able to find some element but the JavaScript console on chrome found it.

So I tried adding a "return" string in the execute script method, which in your case would be:

browser = driver.Chrome()
myElement = browser.execute_script("return document.getElementById('element_id')")

You can also do different operations like you do with Selenium Web-elements.

Example:

browser = driver.Chrome()
elementList = browser.execute_script("return document.getElementsByClassName('element_class_name')")
elementList[0].click() # Clicks the first element from list

I hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

-1

From the js doc (python api can be found there)

If the script has a return value (i.e. if the script contains a return statement), then the following steps will be taken for resolving this functions return value: - For a HTML element, the value will resolve to a webdriver. WebElement - Null and undefined return values will resolve to null
- Booleans, numbers, and strings will resolve as is Functions will resolve to their string representation - For arrays and objects, each member item will be converted according to the rules above

P.S. Why you need to find element using executeScript?

1 Comment

Because it is my task :) So, ok: I have variable called returned_js And i need to assign some value of JavaScript return to this var.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.