9

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>
1

4 Answers 4

11

The function you want is getText().

String text = driver.findElement(webdriver.By.xpath("//div/span")).getText();
Sign up to request clarification or add additional context in comments.

3 Comments

This is Java. I want to do it using nodejs/javascript
@MarkAmery The functions are usually similarly named across languages
Answer in Java coding language instead of Javascript
4
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.

Comments

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

This will return the text within that element.

Comments

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

console.log(element);

Not tested, but this will do.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.