如何使用 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.tw/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+ 瀏覽

開啟您的 職業生涯

完成課程並獲得認證

開始
廣告