2016-01-23 97 views
2

我正在尝试编写一个通用Web驱动程序等待等待元素可点击。但是我发现了网络驱动程序等待写入特定于By.id或By.name的等待。如何在Selenium中编写通用Web驱动程序等待

假设下面是两个WebElements

public WebElement accountNew() { 
    WebElement accountNew = driver.findElement(By.xpath("//input[@title='New']")); 
    waitForElementtobeClickable(accountNew); 
    return accountNew; 
} 

public WebElement accountName() { 
    WebElement accountName = driver.findElement(By.id("acc2")); 
    waitForElementtobeClickable(accountName); 
    return accountName; 
} 

下面是广义waitofrelementtobeclickable。

public static void waitForElementtobeClickable(WebElement element) {   
     try { 
      WebDriverWait wait = new WebDriverWait(driver, 10); 
      wait.until(ExpectedConditions.elementToBeClickable(element)); 
      System.out.println("Got the element to be clickable within 10 seconds" + element); 
     } catch (Exception e) { 
      WebDriverWait wait1 = new WebDriverWait(driver, 20); 
      wait1.until(ExpectedConditions.elementToBeClickable(element)); 
      System.out.println("Got the element to be clickable within 20 seconds" + element); 
      e.printStackTrace(); 
     } 
    } 

但它似乎没有工作。任何关于如何为xpath,或id,或class或Css写一个通用代码的建议都可以写出来?

+0

做什么你的意思是“似乎不起作用”?你有错误吗? – Guy

+0

不,没有错误,但对waitforelementclickable的调用只是绕过,并没有通过实际等待10或20秒的过程。示例:登录到Salesforce应用程序后,我希望顶部面板中的userName是可点击的,以便我可以点击它,然后单击注销。但是登录后页面仍然正在加载,程序只是终止,说找不到元素。但是如果我给出20秒的明确睡眠,它就会起作用。所以xpath/locator不是问题。 – Ronnie

回答

1

这个问题不在你的函数中,它在你的driver.findElement中,因为你试图在元素存在于DOM之前找到它。您可以使用隐式等待

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 

这将等待10秒在DOM定位时,之前存在的任何元素。

或者使用显式的等待

WebDriverWait wait = new WebDriverWait(driver, 10); 
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@title='New']"))); 

找到你的元素这将等待长达10秒钟的元素是可见的。

你当然可以(也应该)同时使用。

您可以更改您的代码以类似的东西

public static WebElement waitForElementtobeClickable(By by) { 
    WebDriverWait wait = new WebDriverWait(driver, 10); 
    WebElement element = wait.until(ExpectedConditions.elementToBeClickable(by)); 
    System.out.println("Got the element to be clickable within 10 seconds" + element); 
    return element; 
} 

public WebElement accountNew() { 
    WebElement accountNew = waitForElementtobeClickable(By.xpath("//input[@title='New']")); 
    return accountNew; 
} 

您发送您的By定位器waitForElementtobeClickable和使用elementToBeClickable(By)代替elementToBeClickable(WebElement),这样你就可以使用XPath,ID,类等

+0

非常感谢。像魅力一样工作。我其实已经有了一个想法,但却无法让我的头脑去实现它。也因为我没有使用Page Factory模型而感到困惑,并且只使用一个静态驱动程序,该驱动程序在BasePage类中声明。 – Ronnie

+0

@罗尼很高兴工作。通过点击附近的绿色复选标记,随意接受此答案作为解决方案;) – Guy

相关问题