如何在 Selenium 中從文字框獲取已輸入的文字?


我們可以使用 Selenium WebDriver 從文字框中獲取已輸入的文字。要獲取 html 文件中元素的 value 屬性,我們必須使用 getAttribute() 方法。然後,value 作為引數傳遞給該方法。

讓我們考慮一個文字框,我們在其中輸入了一些文字,然後想要獲取已輸入的文字。

如果我們監視元素,我們會發現 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://tutorialspoint.tw/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // identify element
      WebElement l = driver.findElement(By.id("gsc-i-id1"));
      // enter texts
      l.sendKeys("Selenium");
      // get value attribute with getAttribute()
      String val = l.getAttribute("value");
      System.out.println("Entered text is: " + val);
      driver.quit()
   }
}

輸出

更新於:2020 年 9 月 18 日

17K + 閱讀次數

開啟你的職業生涯

完成課程取得認證

開始
廣告