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(); 
3
  • 2
    This is Java. I want to do it using nodejs/javascriptCommentedSep 6, 2013 at 6:09
  • 1
    @MarkAmery The functions are usually similarly named across languagesCommentedJul 16, 2016 at 13:43
  • Answer in Java coding language instead of JavascriptCommentedNov 28, 2017 at 11:27
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.

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

    This will return the text within that element.

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

      Not tested, but this will do.

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.