Manu K Mohan
Manu K Mohan

Reputation: 833

Get text from XPath located Element using Selenium WebDriver with JavaScript

I am trying to find an element using xpath and get the elements text value.

For example, I can find the element using xpath in the following way

driver.findElement(webdriver.By.xpath("//div/span));

But I want to get the text of this particular element by using JavaScript.

HTML content is like below

<div><span>Inner Text</span></div>

Upvotes: 9

Views: 84099

Answers (4)

ShaBANG
ShaBANG

Reputation: 193

const By = webdriver.By;

driver.findElement(By.xpath('//div/span'))
    .then(span => span.getText())
    .then(text => console.log(text))

Most of the actions in the webdriver for node/'javascript' return a promise, you have to do a .then to actually get the values.

Upvotes: 4

Cute Developer
Cute Developer

Reputation: 7

var element = driver.findElement(By.xpath("xpath")).getText();

console.log(element);

Not tested, but this will do.

Upvotes: -2

Puneet Sharma
Puneet Sharma

Reputation: 11

WebDriver driver;
String getText = driver.findElement(By.xpath("your xpath")).getText(); 

This will return the text within that element.

Upvotes: 0

Nathan Merrill
Nathan Merrill

Reputation: 8396

The function you want is getText().

String text = driver.findElement(webdriver.By.xpath("//div/span")).getText();

Upvotes: 11

Related Questions