首页 > 解决方案 > 我如何在方法中使用(WebElement webdriverWait until element is clickable)并调用该方法以重新使用

问题描述

根据我下面的代码,我需要定期使用等待元素。有什么方法可以通过调用方法重新使用此代码?

任何帮助或建议将不胜感激。

public static By header = By.xpath("//*[@id=\'content\']/h1");

 public static void ClickLink_Accounts() throws IOException {
    WebDriverWait wait = new WebDriverWait(driver, 50);
    WebElement wait2 = wait.until(ExpectedConditions.elementToBeClickable(header));
    find(Accounts).isDisplayed();
    CaptureScreenshot.Screenshot(driver,"Application HomePage-");
}

public static void ClickLink_Tasks() throws IOException {
    WebDriverWait wait = new WebDriverWait(driver, 50);
    WebElement wait2 = wait.until(ExpectedConditions.elementToBeClickable(header));
    find(Tasks).isDisplayed();
    CaptureScreenshot.Screenshot(driver,"Application HomePage-");
}

标签: javaseleniumclasswait

解决方案


我认为你正在寻找的是这样的

public static void ClickLink_Accounts() throws IOException
{
    waitForHeader();
    find(Accounts).isDisplayed();
    CaptureScreenshot.Screenshot(driver, "Application HomePage-");
}

public static void ClickLink_Tasks() throws IOException
{
    waitForHeader();
    find(Tasks).isDisplayed();
    CaptureScreenshot.Screenshot(driver, "Application HomePage-");
}

public static void waitForHeader()
{
    new WebDriverWait(driver, 50).until(ExpectedConditions.elementToBeClickable(header));
}

但是...当我查看您的两个 ClickLink* 方法时,我看到了很多重复的代码。我会寻找一种方法将这两个(可能还有其他未来的方法)组合成一个接受参数的方法。我假设Accounts并且TasksBy定位器,因为您正在传递一个方法find()?如果是这样,你可以这样做

public static void ClickLink(By locator) throws IOException
{
    waitForHeader();
    find(locator).isDisplayed();
    CaptureScreenshot.Screenshot(driver, "Application HomePage-");
}

并显着简化您的代码。有关详细信息,请参阅干燥


推荐阅读