如何按" TAB"然后"输入" Selenium WebDriver使用Java的关键?

时间:2015-04-21 09:41:03

标签: java selenium selenium-webdriver tabs

我正在使用带有Selenium WebDriver的java进行自动化测试。我想点击标签。我想查看标签功能。

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

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

我有一个包含多个字段的表单,我想跟踪按键标签键是我的控件成功移动到下一个字段。另外,我想检查下面我的控件是image

但是如何逐个点击选项卡。 基本上我需要按Tab键,然后按Enter键点击按钮。

我学习硒。 请帮我。提前谢谢。

4 个答案:

答案 0 :(得分:2)

请参阅适用于我的示例表单的解决方案

FormTab.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();

答案 1 :(得分:2)

尝试下面的代码。这很好。

        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();

答案 2 :(得分:0)

Actions builder = new Actions(driver);
        Action enter= builder
                .keyDown(Keys.TAB)
                .build();
enter.perform();

 Action releaseEnter= builder
                .keyUp(Keys.ENTER)
                .build();
releaseEnter.perform();

答案 3 :(得分:0)

当你在页面上时,你可以尝试使用java的机器人类来模拟按下标签并输入任何其他按钮。