Getting javascript return value in Selenium

I use Selenium2 for some automated tests of my website, and I would like to get the return value of some Javascript code. If I have a foobar() Javascript function in my webpage and I want to call this and get the return value in my Python code, what can I do to do this?

+86
javascript python selenium selenium-webdriver
Apr 07 2018-11-17T00:
source share
2 answers

To return a value, simply use the return JavaScript keyword in the string passed to the execute_script() method, for example.

 >>> 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' 
+148
Apr 07 2018-11-17T00:
source share
β€” -

You can return values ​​even if you don’t have a piece of code written as a function, as in the code example below, simply by adding return var; at the end, where var is the variable you want to return.

 result = driver.execute_script('''cells = document.querySelectorAll('a'); URLs = [] console.log(cells); [].forEach.call(cells, function (el) { if(el.text.indexOf("download") !== -1){ //el.click(); console.log(el.href) //window.open(el.href, '_blank'); URLs.push(el.href) } }); return URLs''') 

result will contain an array that is in the URLs this case.

+1
Dec 28 '17 at 12:46 on
source share



All Articles