如何使用 selenium 為 web 元素的“value”賦值?


我們可以使用 Selenium webdriver 來為輸入 web 元素賦值。我們可以藉助 sendKeys 方法來向輸入欄位輸入文字。要輸入的值作為引數傳遞給該方法。

語法

driver.findElement(By.id("txtSearchText")).sendKeys("Selenium");

我們還可以使用 Selenium 中的 Javascript 執行器來執行輸入編輯框文字之類的 web 操作。我們將使用 executeScript 方法,並將 引數 index.value='<要輸入的值>'webelement 作為引數傳遞給該方法。

語法

WebElement i = driver.findElement(By.id("id"));
JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript("arguments[0].value='Selenium';", i);

示例

程式碼實現

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.util.concurrent.TimeUnit;
public class SetValue{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://tutorialspoint.tw/about/about_careers.htm");
      // identify element
      WebElement l=driver.findElement(By.cssSelector("input[id*='id']"));
      l.sendKeys("Selenium");
      // obtain the value entered with getAttribute method
      System.out.println("Value entered is: " +l.getAttribute("value"));
      driver.close();
   }
}

示例

使用 Javascript 執行器的程式碼實現。

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class SetValueJS{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://tutorialspoint.tw/about/about_careers.htm");
      // identify element
      WebElement l=driver.findElement(By.cssSelector("input[id*='id']"));
      // Javascript Executor class with executeScript method
      JavascriptExecutor j = (JavascriptExecutor)driver;
      j.executeScript("arguments[0].value='Selenium';", l);
      System.out.println("Value entered is: " +l.getAttribute("value"));
      driver.close();
   }
}

輸出

更新日期:26-Oct-2020

14K+ 瀏覽

職業生涯中邁出第一步

完成課程即可獲得認證

開始
廣告
© . All rights reserved.