【问题标题】:Get user input from IDE/Console in selenium webderiver在 selenium webdriver 中从 IDE/控制台获取用户输入
【发布时间】:2026-02-14 16:10:01
【问题描述】:

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

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

在输入框中我想要生成什么用户类型然后我想通过 selenium 发送?

【问题讨论】:

  • 您想获取您使用 sendkeys() 发送的值“1121”吗?

标签: java eclipse selenium selenium-webdriver user-input


【解决方案1】:

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

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

否则,如果您需要从其中一个 web 元素中获取文本,请识别该 web 元素并使用 getText() 获取字符串值。

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

希望这会有所帮助。谢谢..

【讨论】:

  • 我想从网站获取
【解决方案2】:

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

使用Scanner,您将在IDE 控制台上获得用户提示Enter your Email or Phone :。请记住通过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();
    }

}

【讨论】:

    【解决方案3】:

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

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

    程序输出将是“1121”

    【讨论】:

      【解决方案4】:

      您可以使用 Nodejs Readline 作为我的 github example 等待用户输入

      【讨论】: