Java 如何从硒的跨度类中获取文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22216167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:23:02  来源:igfitidea点击:

How to get text from span class in selenium

javaseleniumselenium-webdriver

提问by MBA

<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"

如何从 selenium 中的 span 标签中提取文本。是通过类名,但所有四个类 = "firstLanguage"

回答by Elliott Frisch

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

我相信你可以使用nth-child伪类来做到这一点,例如

.firstLanguage:nth-child(2)

回答by Shishir Kumar

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 firstLanguageand you can iterate the list to take text out of them.

这将返回类定义的所有 span 元素firstLanguage,您可以迭代列表以从中取出文本。

回答by VS Achuthanandan

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

will display "Zeit"

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

将显示“ Zeit

driver.findElement(By.xpath("/html/body/span[2]")).getText();
将显示“ Nach

likewise

同样地




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


将显示“Gleis格莱斯

回答by user3387003

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.

将显示所有元素。

回答by rsakhale

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

更好的实现是通过使用 findElements,请检查下面的代码

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']