提问者:小点点

如何按"TAB"然后"ENTER"键在Selenium WebDriver使用Java?


我正在使用Selenium WebDriverjava进行自动化测试。我想单击选项卡。我想检查选项卡功能。

我可以使用Tab键获取按钮如下:

WebElement webElement = driver.findElementByXPath("");
webElement.sendKeys(Keys.TAB);
webElement.sendKeys(Keys.ENTER);

但是我如何逐个点击标签。基本上我需要实现按Tab键,然后按Enter键点击按钮。

我正在学习硒。请帮帮我。事先谢谢。


共3个答案

匿名用户

请参阅与我的示例表单一起使用的解决方案

FormTabc. html:

<!DOCTYPE html>
<html>
<body>
<form>
    First name:<br>
    <input type="text" name="firstname" value="Mickey">
    <br>
    Last name:<br>
    <input type="text" name="lastname" value="Mouse">
    <br><br>
    <input type="submit" name="submit" value="Submit">
</form>
<p>If you click "Submit", nothing happens.</p>
</body>
</html>

Java代码:

WebDriver driver = new FirefoxDriver();

//Insert path to your file
driver.get("FormTab.html");

//Three example elements
WebElement firstField = driver.findElement(By.name("firstname"));
WebElement secondField = driver.findElement(By.name("lastname"));
WebElement submit = driver.findElement(By.name("submit"));

//Start with the first field
firstField.sendKeys();
//Verify that we in the first field
if(driver.switchTo().activeElement().equals(firstField))
    System.out.println("First element is in a focus");
else
    //Add Assertion here - stop execution
    System.out.println("ASSERTION - first element not in the focus");

firstField.sendKeys(Keys.TAB);

//Verify that we in the second field
if(driver.switchTo().activeElement().equals(secondField))
    System.out.println("Second element is in a focus");
else
    //Add Assertion here - stop execution
    System.out.println("ASSERTION - second element not in the focus");

secondField.sendKeys(Keys.TAB);

if(driver.switchTo().activeElement().equals(submit))
    System.out.println("Submit element is in a focus");
else
    //Add Assertion here - stop execution
    System.out.println("ASSERTION - submit element not in the focus");

//Click the button 
submit.click();

//Need be closed also in case the assertion - use @After
driver.close();

匿名用户

试试下面的代码。这工作正常。

        Actions builder = new Actions(driver);         
        builder.SendKeys(OpenQA.Selenium.Keys.Tab).Build().Perform();
        builder.Release().Perform();            
        builder.SendKeys(OpenQA.Selenium.Keys.Tab).Build().Perform();
        builder.Release().Perform();

匿名用户

您可以尝试使用机器人类的java来模拟按下选项卡,并在页面上输入任何其他按钮。