在selenium webderiver中从IDE / Console获取用户输入

我想从用户输入中获取密钥(发送密钥)我应该如何实现它?

driver.findElement(By.xpath(".//*[@id='vehicleNum']")).sendKeys("1121"); 

作为演示,我将为您提供与URL https://accounts.google.com的示例代码块,该代码块将要求用户输入提供Email or Phone ,然后单击“ Next按钮:

使用Scanner您将在IDE控制台上获得用户提示,如Enter your Email or Phone : 。 请记得通过scanner_user.close();显式关闭扫描程序scanner_user.close(); 防止Resource Leakage

 import java.util.Scanner; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class GMAIL_LOGIN_SCANNER { public static void main(String[] args) { Scanner scanner_user, scanner_pass; System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe"); ChromeOptions options = new ChromeOptions(); options.addArguments("start-maximized"); options.addArguments("disable-infobars"); options.addArguments("--disable-extensions"); WebDriver driver = new ChromeDriver(options); driver.get("https://accounts.google.com"); driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS); scanner_user = new Scanner(System.in); System.out.println("Enter your Email or Phone : "); String user = scanner_user.nextLine(); driver.findElement(By.xpath("//input[@id='identifierId']")).sendKeys(user); driver.findElement(By.id("identifierNext")).click(); scanner_user.close(); } } 

您可以使用内置的Scanner类从系统控制台获取输入。 下面的代码可能会给你一些想法。

 Scanner sc = new Scanner(System.in); String name = sc.nextLine(); //now pass name in sendkeys. driver.findElement(By.xpath(".//*[@id='vehicleNum']")).sendKeys(name); 

否则,如果您需要从其中一个webelement获取文本,请标识webelement并使用getText()来获取字符串值。

 String value = driver.findElement(by.xpath("//")).getText(); driver.findElement(By.xpath(".//*[@id='vehicleNum']")).sendKeys(value); 

希望这可以帮助。 谢谢..

即使你的问题也不清楚,但我认为你需要在解决方案之下。 要从文本框中获取输入值,您可以使用以下代码:

  driver.findElement(By.xpath(".//*[@id='vehicleNum']")).sendKeys("1121"); String str = driver.findElement(By.xpath(".//*[@id='vehicleNum']")).getAttribute("value"); System.out.println(str); 

节目输出为“1121”