learning
learning

Reputation: 47

Get text found between span - selenium

Inspect element from Google Chrome:

<div class="form-style-abc">
   <fieldset>
    <legend><span class="number">*</span>Search Zone</legend>

Need to retrieve the "Search Zone", however im unable to perform the search and getText()

I had performed the following on Eclipse but getting error:

Code:

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

Error Message:

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//span[@class = 'number']"}

Upvotes: 0

Views: 849

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193338

As per the HTML you have provided to extract the text Search Zone you can use the following line of code :

String HeaderTxt = driver.findElement(By.xpath("//div[@class='form-style-abc']/fieldset/legend[(self::legend) and not (@class='number')]")).getText();
System.out.println(HeaderTxt);

Update 1

As per your comment update as you are still 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());

Update 2

As you mentioned the element is within an <iframe> tag you need to switch to the exact frame and then look out for the WebElement. Here you can find a detailed discussion on How to switch to frame in Selenium Webdriver Java


Update 3

Xpath Explanation

Through the xpath as "//div[@class='form-style-abc']/fieldset/legend" we have reached till the <legend> node. Now you want to get the text Search Zone only. So being within the <legend> tag you have to trim the child <span> tag which have a class as number. So we added a clause within our xpath not to consider (@class='number') while retrieving the text as in :

String HeaderTxt = driver.findElement(By.xpath("//div[@class='form-style-abc']/fieldset/legend[(self::legend) and not (@class='number')]")).getText();

Upvotes: 1

Related Questions