如何在 Selenium 中提取 Web 元素的文本?
software testingautomation testingselenium web driver更新于 2026/2/10 15:52:17
Selenium 使用 getText() 方法提取 Web 元素的文本。
使用 getText() 的代码实现。
示例
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ExtractText {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/index.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
//使用带有 # 的 id 作为 CSS 表达式
driver.findElement(By.cssSelector("#gsc-i-id1")).sendKeys("Selenium");
// 使用 getText() 提取控制台中输入的文本
System.out.println(“输入的文本是:” driver.findElement(By.cssSelector("#gsc-i- id1")).getText());
driver.close();
}
}

