如何在 Selenium 中获取文本框中输入的文本?

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

我们可以在 Selenium webdriver 中获取文本框中输入的文本。要获取 HTML 文档中元素的 value 属性,我们必须使用 getAttribute() 方法。然后将值作为参数传递给该方法。

假设我们在一个文本框中输入了一些文本,然后想要获取输入的文本。

如果我们监视该元素,我们会发现在 html 代码中该元素没有 value 属性。

在该字段中输入文本后,我们可以使用 getAttribute() 方法获取输入的文本。

示例

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 GetValAttribute{
   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(4, TimeUnit.SECONDS);
      // 识别元素
      WebElement l = driver.findElement(By.id("gsc-i-id1"));
      // 输入文本
      l.sendKeys("Selenium");
      // 使用 getAttribute() 获取值属性
      String val = l.getAttribute("value");
      System.out.println("Entered text is: " + val);
      driver.quit()
   }
}

输出


相关文章