Get Text from Xpath Located Element Using Selenium Webdriver with Javascript

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

4 Answers

The function you want is getText().

String text = driver.findElement(webdriver.By.xpath("//div/span")).getText();
3
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.

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

This will return the text within that element.

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

console.log(element);

Not tested, but this will do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.