如何获取 span 之间的文本 – Selenium
seleniumautomation testingtesting tools
我们可以使用 Selenium webdriver 获取 span 标签内的文本。
可以使用 getText 方法捕获 Web 元素的文本。让我们看一个元素的示例,其中 span 标签内包含文本 - © Copyright 2021. All Rights Reserved。

语法
WebElement l = driver.findElement(By.xpath("//p/span"));
String s = l.getText();
示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class SpanText{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//隐式等待
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//最大化窗口
driver.manage().window().maximize();
//URL 启动
driver.get("https://www.tutorialspoint.com/index.htm");
// 使用 Javascript Executor 滚动到元素
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
// 识别带有 span 的元素并获取文本
WebElement l = driver.findElement(By.xpath("//p/span"));
String s = l.getText();
System.out.println("Text is: " + s);
driver.quit();
}
}
输出


