I'm using Selenium2 for some automated tests of my website, and I'd like to be able to get the return value of some Javascript code. If I have a foobar()
Javascript function in my webpage and I want to call that and get the return value into my Python code, what can I call to do that?
Asked
Active
Viewed 1.1e+01k times
123

Eduard Florinescu
- 16,747
- 28
- 113
- 179

Eli Courtwright
- 186,300
- 67
- 213
- 256
2 Answers
203
To return a value, simply use the return
JavaScript keyword in the string passed to the execute_script()
method, e.g.
>>> from selenium import webdriver
>>> wd = webdriver.Firefox()
>>> wd.get("http://localhost/foo/bar")
>>> wd.execute_script("return 5")
5
>>> wd.execute_script("return true")
True
>>> wd.execute_script("return {foo: 'bar'}")
{u'foo': u'bar'}
>>> wd.execute_script("return foobar()")
u'eli'

Eli Courtwright
- 186,300
- 67
- 213
- 256
-
1if the variable is not defined by javascript, what would be the return value?Does it throw an exception or simply an empty string ? – Alex Sep 08 '15 at 00:01
-
if variable is not defined, it returns `None` – dbJones Oct 26 '15 at 22:43
-
7quick note for those newbs, `return_value = wd.execute_script("return {foo: 'bar'}")` would store the returned value to be used later in your program. – ntk4 Sep 24 '16 at 04:47
-
1the [doc](https://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.execute_script) lacks specifying a **Retruns:** note. Although in teir **Usage:** sample they put a js which returns the document title. Better to explicitly specify **Retruns:** in their doc – woodz Mar 14 '19 at 13:36
20
You can return values even if you don't have your snippet of code written as a function like in the below example code, by just adding return var;
at the end where var is the variable you want to return.
result = driver.execute_script('''
cells = document.querySelectorAll('a');
URLs = [];
[].forEach.call(cells, function (el) {
URLs.push(el.href)
});
return URLs
''')
result
will contain the array that is in URLs
this case.

Eduard Florinescu
- 16,747
- 28
- 113
- 179