Fix Python – Getting the return value of Javascript code in Selenium


Asked By – Eli Courtwright

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?

Now we will see solution for issue: Getting the return value of Javascript code in Selenium


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")
>>> wd.execute_script("return true")
>>> wd.execute_script("return {foo: 'bar'}")
{u'foo': u'bar'}
>>> wd.execute_script("return foobar()")

This question is answered By – Eli Courtwright

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0