Get text from XPath located Element using Selenium WebDriver with JavaScript

61,849

Solution 1

The function you want is getText().

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

Solution 2

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.

Share:
61,849
Manu K Mohan
Author by

Manu K Mohan

Front end developer all the time 10 plus years of experience in Front development. 6 years experienced in Angular. Interested in working towards the future of user interface.

Updated on July 09, 2022

Comments

  • Manu K Mohan
    Manu K Mohan almost 2 years

    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>
    
  • Manu K Mohan
    Manu K Mohan almost 11 years
    This is Java. I want to do it using nodejs/javascript
  • Nathan Merrill
    Nathan Merrill almost 8 years
    @MarkAmery The functions are usually similarly named across languages
  • zishan paya
    zishan paya over 6 years
    Answer in Java coding language instead of Javascript