尝试抓住直到成功java

时间:2018-12-12 20:20:07

标签: java selenium try-catch

我收到过时元素引用异常。如果我可以单击一下。 我要单击元素,直到5次找到该对象。

我如何尝试捕获块循环,直到找到单击或元素? 我希望它尝试在失败之前单击元素5次。 我使用下面的代码,但无法正常工作。

点击方法:

public void click1(WebDriver driver, WebElement element, String name) {    
    int attempts = 0;
    while(attempts < 5) {
        try {
            element.click();
            Add_Log.info("Successfully clicked on  " + name);
            Reporter.log("Successfully clicked on " + name);
            break;
        } catch (Exception e) {
            try {
                JavascriptExecutor executor = (JavascriptExecutor) driver;
                executor.executeScript("arguments[0].click();", element);
                Add_Log.info("Successfully clicked on  " + name);
                Reporter.log("Successfully clicked on " + name);
                break;
            } catch (Exception e2) {
                Add_Log.info("Not able to click " + name);
                Reporter.log("Not able to click " + name);
                TestResultStatus.Testfail = true;
                Assert.fail();
            }
        }
        attempts++;
    }
}

2 个答案:

答案 0 :(得分:0)

这实际上就像将循环条件从attempts < 5更改为true并删除attempts++;行一样简单。至少我从您的问题中了解了这一点。如果这不是您要查找的内容,请尝试更清楚地表述该问题。

答案 1 :(得分:-1)

我会像下面这样写。您尝试进行5次正常点击,两次尝试之间会短暂暂停。如果引发异常,则将其吃掉并进行另一次尝试。如果这5个都不成功,则尝试使用JS单击它。如果失败,则记录失败等。

public void click1(WebDriver driver, WebElement element, String name) {    
    int attempts = 0;
    while(attempts < 5) {
        try {
            element.click();
            Add_Log.info("Successfully clicked on " + name);
            Reporter.log("Successfully clicked on " + name);
            return;
        } catch (Exception e) {
        }
        attempts++;
        Thread.Sleep(500); // brief pause between attempts
    }

    try {
        JavascriptExecutor executor = (JavascriptExecutor) driver;
        executor.executeScript("arguments[0].click();", element);
        Add_Log.info("Successfully clicked on " + name);
        Reporter.log("Successfully clicked on " + name);
        return;
    } catch (Exception e2) {
        Add_Log.info("Not able to click " + name);
        Reporter.log("Not able to click " + name);
        TestResultStatus.Testfail = true;
        Assert.fail("Not able to click " + name);
    }
}

注意:在尝试单击元素之前,最好等待该元素可单击。这可能会解决您的大多数问题。您仍然可能会遇到一些对话框/横幅/微调器与您需要处理的元素重叠的问题...并且可以通过尝试5次单击来解决该问题,等等。