我正在尝试编写一个通用的Web驱动程序,等待元素可单击。但我在网上发现了Web驱动程序等待特定于By.id或By.name。
假设以下是两个Web元素
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;
}
以下是可以点击的广义waitofrelement。
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 :(得分:1)
问题不在您的函数中,而是在driver.findElement
中,因为您尝试在元素存在于DOM之前找到它。您可以使用隐式等待
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
在查找DOM之前,任何元素都会等待10秒钟。
或使用显式等待
找到您的元素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,class等。