Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value from JavaScript using Selenium?

I executed JavaScript using this advice and I want to return a value from this script.

like image 526
r_D Avatar asked Nov 22 '16 06:11

r_D


People also ask

How do you read a Javascript variable in Selenium Webdriver?

We can read Javascript variables with Selenium webdriver. Selenium can run Javascript commands with the help of executeScript method. The Javascript command to be executed is passed as an argument to the method. Also we have to add the statement import org.

Can Selenium interact with Javascript?

You an use selenium to do automated testing of web apps or websites, or just automate the web browser. It can automate both the desktop browser and the mobile browser. Selenium webdriver can execute Javascript. After loading a page, you can execute any javascript you want.

Can we use XPath in JavascriptExecutor?

In Selenium Webdriver, locators like XPath, CSS, etc. are used to identify and perform operations on a web page. In case, these locators do not work you can use JavaScriptExecutor.


1 Answers

You can just return the value like this:

Java:

JavascriptExecutor js = (JavascriptExecutor) driver;         
js.executeScript("return document.title");

Python:

driver.execute_script("return document.title")
driver.execute_script("return document.querySelector('.somecssclass')")
like image 119
Jochen Avatar answered Sep 20 '22 06:09

Jochen