为什么我的WebDriver等待方法不能一直点击按钮?

时间:2017-05-05 15:54:46

标签: java selenium selenium-webdriver webdriver

为什么我的WebDriver等待方法不能一直点击按钮?

例如,在每100个测试中,7个将无法说明定位器不可见,但是当查看屏幕截图时,按钮显然在那里!

<input class="btn btn-default dropdown-toggle buynow" aria-expanded="false" value="Buy Now" type="submit"/>

我已经尝试过等待,正常点击,循环和JS点击等等,而不是一直点击按钮。

    public void waitAndClickElement(WebElement element) throws InterruptedException {
    boolean clicked = false;
    int attempts = 0;
    while (!clicked && attempts < 1000) {
        try {
            wait.until(ExpectedConditions.elementToBeClickable(element)).click();
            System.out.println("Successfully clicked on the WebElement: " + element.toString());
            clicked = true;
        } catch (Exception e) {
            System.out.println("Unable to wait and click on WebElement" + element + ", Exception: " + e.getMessage());
            Assert.fail("Method failed: waitAndClickElement");
            //Assert.fail("Unable to wait and click on the WebElement, using locator: " + element.toString());
        }
        attempts++;
    }

}

public void clickOnBuyNowButton() throws InterruptedException {
    WebElement buyNowButton = driver.findElement(By.xpath("html/body/div[1]/div[3]/div[1]/div/div/section/div[2]/div[2]/div[2]/form/div/input"));
    WaitUntilWebElementIsVisible(buyNowButton);
    Actions action = new Actions(driver);
    action.moveToElement(buyNowButton).doubleClick().build().perform();
}

有什么想法吗?我做错了吗?

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

尝试以下内容;在这里,我首先等待一个元素可点击,然后一旦它变得可点击我移动到它然后抛出我的点击:

WebDriverWait wait = new WebDriverWait (driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(yourElement));

Actions act = new Actions(driver);
act.moveToEelment(yourElement).click().build().perform();