如何使用 Selenium Web Driver 来获取 HTML 输入的值。


我们能够用 Selenium webdriver 获取一个 HTML 输入的值。这通过 getAttribute() 方法实现。要获取标签名为输入的字段的 value ,我们需要将该值作为参数传递到 getAttribute() 方法。

我们考虑一个 HTML 输入的 HTML 代码。

我们没有值属性为该字段的 DOM。然而,我们将获取用 getAttribute() 方法显示的字段值。

示例

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 InputVal{
   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://tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // identify element and enter text
      WebElement l = driver.findElement(By.id("gsc-i-id1"));
      l.sendKeys("Selenium");
      // getAttribute() to get value as displayed in GUI
      String val = l.getAttribute("value");
      System.out.println("The input value: "+ val);
      driver.quit()
   }
}

输出

更新于:18-Sep-2020

13K+ 浏览

开启您的 职业生涯

完成课程并获得认证

开始
广告