如何从 Selenium 元素 WebElement 对象中获取文本?

seleniumautomation testingtesting tools更新于 2026/2/11 11:07:17

我们可以使用 Selenium webdriver 从 WebElement 中获取文本。getText() 方法获取元素的内部文本。它会获取可见元素及其子元素的文本。它会忽略尾随和前导空格。

首先,我们需要借助 id、 class、name、xpath 或 css 等定位器来识别元素,然后对其应用 getText() 方法获取元素的文本内容。

让我们获取页面上元素 About Careers at Tutorials 的文本−

示例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class GetElementText{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // 识别元素
      WebElement p=driver.findElement(By.xpath("//h1"));
      //getText() 获取文本
      String s= p.getText();
      System.out.println("Text content is : " + s);
      driver.close();
   }
}

输出


相关文章