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

我想收到所有新产品和发布的文字我正在尝试这个

driver.findElement(By.xpath(".//*[@id='iselmf-folder-detail']/h2/span")).getText();

但它正在打印文件夹

<h2 class="iselmf-h2-icon">
<span>Folder:</span>
All New Products and Launches
</h2>
stack overflow How to get text from span in selenium
原文答案

答案:

作者头像

The text is in the <h2> tag, not the <span> tag. Try

driver.findElement(By.xpath(".//*[@id='iselmf-folder-detail']/h2")).getText();
作者头像

Look at the HTML tags

<span>Folder:</span>

The /span indicates that this is the end of the span, so if you're using the span as the identifier then it will only return folder.

The parent element of the span is the h2 tag. So to get everything between h2 and /h2 tags you need to do this -

driver.findElement(By.xpath(".//*[@id='iselmf-folder-detail']/h2")).getText();
作者头像

Two ways to do this,

1) driver.findElement(By.xpath(".//*[@id='iselmf-folder-detail']/h2")).getText();

2) Get the text from both and then concatenate it, something like

String firstblock = driver.findElement(By.xpath(".//*[@id='iselmf-folder-detail']/h2")).getText();
String secondblock = driver.findElement(By.xpath(".//*[@id='iselmf-folder-detail']/h2/span")).getText(); 
String finaltext= firstblock+secondblock;
作者头像

span 属性获取文本时,我遇到了非常相似的问题。解决方案是像这样使用 .getAttribute("value")

driver.findElement(By.xpath(".//*[@id='iselmf-folder-detail']/h2/span")).getAttribute("value");

**String org.openqa.selenium.WebElement.getAttribute(String name)**