MBA
MBA

Reputation: 41

How to get text from span class in selenium

<th>     
    <span class="firstLanguage">Zeit</span>
</th>
<th>
    <span class="firstLanguage">Nach</span>
</th>
<th>
    <span class="firstLanguage"> </span>
</th>
<th>
    <span class="firstLanguage">Über</span>
</th>
<th>
    <span class="firstLanguage">Gleis</span>
</th>

How can I extract the text from span tags in selenium. Is it via classname, but all four class = "firstLanguage"

Upvotes: 4

Views: 33717

Answers (5)

Shishir Kumar
Shishir Kumar

Reputation: 8201

You can try below snippet.

 int count = selenium.getXpathCount("//span[@class='firstLanguage']").intValue();
 for(int i =1 ; i <= count ; i ++){
         System.out.println(selenium.getText("//span["+i+"]"));
 }

This will return you all the span elements defined by the class firstLanguage and you can iterate the list to take text out of them.

Upvotes: 4

rsakhale
rsakhale

Reputation: 1036

Better implementation would be by making use of findElements, please check below code

List<WebElement> elements = driver.findElements(By.className("firstLanguage"));
for(WebElement element : elements){
   System.out.println(element.getText());
}

You can also make use of other locators as below

xpath = //th//span[@class='firstLanguage']

css = th span[class='firstLanguage']

Upvotes: 0

user3387003
user3387003

Reputation: 1

Using this code:

 List<WebElement> elements =driver.findElements(By.xpath("//*/div/table/tbody/tr/th/span"));
            for(WebElement ele:elements)
            {
            System.out.println(ele.getText());
            }

will display all the elements.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201437

I believe you can use the nth-child pseudoclass to do that, for example

.firstLanguage:nth-child(2)

Upvotes: 1

VS Achuthanandan
VS Achuthanandan

Reputation: 111

driver.findElement(By.xpath("/html/body/span")).getText();

will display "Zeit"

driver.findElement(By.xpath("/html/body/span[2]")).getText();
will display "Nach"

likewise


driver.findElement(By.xpath("/html/body/span[5]")).getText();
will display "Gleis"

Upvotes: 3

Related Questions