如何使用 Selenium Webdriver 從文字框中獲取輸入的文字?


我們可以使用 Selenium webdriver 從文字框中獲取輸入的文字。首先,我們必須使用 sendKeys 方法在文字框中輸入文字(在使用任何定位器識別出來之後)。

然後應用 getAttribute 方法以獲取在該欄位中輸入的文字,並將引數值傳遞給該方法。讓我們嘗試獲取在谷歌搜尋框中輸入的值 −

語法

WebElement m = driver.findElement(By.name("q"));
String st = m.getAttribute("value");

示例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class GetTextTyped{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.google.com/");
      // identify element
      WebElement t =driver.findElement(By.name("q"));
      t.sendKeys("Tutorialspoint");
      // obtain value with getAttribute
      System.out.println("Value is: " + t.getAttribute("value"));
      driver.quit();
   }
}

輸出

更新於: 03-Apr-2021

3K+ 檢視次數

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.