如何在 Selenium 中获取编辑框的值?


我们可通过以下方式在 Selenium 中获得编辑框的值:

  • 使用 getText() 方法。

  • 使用 JavascriptExecutor 类。

使用 getText() 方法实现代码。

示例

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 GetValueScripting {
   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(12, TimeUnit.SECONDS);
      String text = driver.findElement(By.className("gsc-input")).getText();
      System.out.println("Extracted text is " + text);
      driver.close();
   }
}

使用 JavascriptExecutor 类实现代码。

示例

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;
import org.openqa.selenium.JavascriptExecutor;
public class ExtractValueScripting {
   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(12, TimeUnit.SECONDS);
      // create Javascript object
      JavascriptExecutor js = (JavascriptExecutor)driver;
      // Issue command to extract the text
      String text = js.executeScript("return document.getElementById(' gsc-i-id1').value").toString();
      System.out.println("Extracted text is" + text);
      driver.close();
   }
}

更新于: 10-06-2020

491 次浏览

开启您的 职业生涯

完成课程以获得认证

立即开始
广告
© . All rights reserved.