Krunal Thakkar
Krunal Thakkar

Reputation: 15

How do I get response of Javascript using JavascriptExecutor in Java selenium or how to extract <script> tag text?

Here I want to get extract the value from the tag. But through the selenium, I am not able to find script tag and fetch data for the same.

But through Javascript, I am able to access that script tag and fetch the value. The script is like below,

<script class="payload-script"> Text </script>

$(".payload-script").text();

but now I want to run this script through JavascriptExecutor and get value to java variable so I can do further processing.

Upvotes: 0

Views: 1113

Answers (1)

Abhishek Dhoundiyal
Abhishek Dhoundiyal

Reputation: 1417

In selenium - JavaScriptExecutor is an interface that provides a mechanism to execute Javascript through selenium driver.

Please use the below code:

JavascriptExecutor jse = (JavascriptExecutor) driver;
String textValue = (String) jse.executeScript("return document.getElementsByClassName('payload-script')[0].text");
System.out.println(textValue);

Another way:

WebElement el = driver.findElement(By.className("payload-script"));
String textValue2 = (String) jse.executeScript("return arguments[0].text", el);
System.out.println(textValue2);

Upvotes: 1

Related Questions