Menu Close

How to get the return value of JavaScript code in Python Selenium?

Sometimes, we want to get the return value of JavaScript code in Python Selenium.

In this article, we’ll look at how to get the return value of JavaScript code in Python Selenium.

How to get the return value of JavaScript code in Python Selenium?

To get the return value of JavaScript code in Python Selenium, we get the return value of the execute_script method.

For instance, we write

from selenium import webdriver

wd = webdriver.Firefox()
wd.get("http://localhost/foo/bar")
val = wd.execute_script("return 5")

to call execute_script to run the "return 5" JavaScript code.

Then we get the returned value from val, which is assigned the return value of execute_script.

Therefore, val is 5.

Conclusion

To get the return value of JavaScript code in Python Selenium, we get the return value of the execute_script method.

Posted in Python, Python Answers