How to get text found between span selenium

0 votes

Inspect element from Google Chrome:

<div class="form-style-abc">

   <fieldset>

    <legend><span class="number">*</span>Search Zone</legend>

I need to retrieve the "Search Zone", however, I’m unable to perform the search and getText(). I had to perform the following on Eclipse but getting an error:

Code:

String HeaderTxt = driver.findElement(By.xpath("//span[@class = 'number']")).getText();

System.out.println(HeaderTxt);


Below is the error message:

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//span[@class = 'number']"}
Jun 18, 2018 in Selenium by Martin
• 4,320 points
78,599 views

6 answers to this question.

0 votes

As you are seeing NoSuchElementException.

Possibly you need to wait for the element inducing WebDriverWait as follows :

WebElement HeaderTxtElem = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='form-style-abc']/fieldset/legend[(self::legend) and not (@class='number')]")));

System.out.println(HeaderTxtElem.getText());

For further understanding, you can refer to the Selenium Certification.

answered Jun 18, 2018 by Samarpit
• 5,910 points
0 votes
String HeaderTxt = driver.findElement(By.xpath("//span[@class = 'number']")).text();

VIA PYTHON 3+

answered Jan 28, 2019 by TazzProductions
Perfect. This works :) Thanks
+1 vote
The text "Search Zone" is not part of the span tag. Instead it is part of the legend tag.
The span tag holds the text "*".

In Python 2.7:
"""elem == name of element"""
elem = driver.find_element_by_xpath("//legend").text
print elem[1:]
answered Feb 28, 2019 by Trying to Figure
0 votes

You can use By. XPath with the code you have​ Inner text is text between the opening tags and closing tags. For example: <a>I Am Inner Text</a> In above example, texts “I Am Inner Text” between opening and closing tags are called inner text of web element “a”.

answered Dec 15, 2020 by Gitika
• 65,730 points