Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the return value of Javascript code in Selenium

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?

like image 643
Eli Courtwright Avatar asked Apr 07 '11 17:04

Eli Courtwright


People also ask

How do I return in Selenium?

We can type Enter/Return key in Selenium. We shall use the sendKeys method and pass Keys. ENTER as an argument to the method. Also, we can use pass Keys.

How do you find the value of an element in Selenium?

The getAttribute() method helps to get the value of any attribute of a web element, which is returned as a String. If an attribute has a Boolean value, the method returns either True or null. Also, if there is no attribute, the method will return null.

What is the return type of JavaScript executor?

executeScript() For an HTML element, this method returns a WebElement. For a decimal, a Double is returned. For a non-decimal number, a Long is returned.

Can Selenium scrape JavaScript?

One of the benefits of Selenium is that it can web-scrape dynamic JavaScript pages where there are dynamic interactions such as hovering over menu items.


1 Answers

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' 
like image 140
Eli Courtwright Avatar answered Oct 03 '22 04:10

Eli Courtwright