真的不需要覆盖.click(),正如@lauda 在 cmets 中所说,这不是一个好习惯。您不需要添加大量代码来等待元素可点击,因此声称它将添加数千行代码的说法是不正确的。您可以使用一行代码轻松完成此操作......因此无需额外的代码行。话虽如此...您应该少关注它将添加和考虑多少行代码:
- 维护起来有多容易?
- 我是否在我的代码库中增加了不必要的复杂性?
- 它会变得更具可读性吗?
- ...等等...
代表按钮的示例点击方法
public void clickButtonX()
{
new WebDriverWait(driver, timeOutInSeconds).until(ExpectedConditions.elementToBeClickable(buttonXLocator)).click();
}
你在类的顶部声明了这些
private By buttonXLocator = By.id("buttonXId");
private int timeOutInSeconds = 10;
话虽如此...我认为这不是正确的方法。使用页面对象模型,您应该让每个页面类句柄等待页面完成加载......然后您不必等待按钮加载之前单击它们。在动态加载按钮的情况下,触发动态加载的动作应该等待加载完成。
package sandbox;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import common.Functions;
public class _PageTemplate
{
private WebDriver driver;
private By dynamicPageLoadLocator = By.id("someId");
private By buttonXLocator = By.id("buttonXId");
private By dynamicLinkLocator = By.id("dynamicLinkId");
private By dynamicSectionElementLocator = By.id("dynamicSectionId");
public _PageTemplate(WebDriver webDriver) throws IllegalStateException
{
Functions.waitForPageLoad(driver);
// see if we're on the right page
if (!driver.getCurrentUrl().contains("samplePage.jsp"))
{
throw new IllegalStateException("This is not the XXXX Sample page. Current URL: " + driver.getCurrentUrl());
}
// for dynamic pages, wait for a specific element to signal the dynamic load is complete
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(dynamicPageLoadLocator));
}
public void clickButtonX()
{
// no wait needed here
driver.findElement(buttonXLocator).click();
}
public void clickDynamicLink()
{
// clicking this link triggers part of the page to change, reload, etc. ...
driver.findElement(dynamicLinkLocator).click();
// ... so after the click, we wait for the dynamic part of the page to finish by locating an element that is inside the dynamically
// loaded portion and wait for it to be visible
new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(dynamicSectionElementLocator));
}
}
这是在某些 Utils 类或其他什么中声明的。
/**
* Waits for the browser to signal that the DOM is loaded. For dynamic pages, an extra wait may be necessary.
*/
public static void waitForPageLoad(WebDriver driver)
{
new WebDriverWait(driver, 30).until(new ExpectedCondition<Boolean>()
{
public Boolean apply(WebDriver webDriver)
{
return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
}
});
}
现在有了这个框架,我们不再需要向每个按钮添加代码来确保它在点击之前可用。我建议您对所有代码都采用这种方法。只在需要的地方等待,而不是到处等待。
- 等待页面加载
- 触发动态换页后,等待换页完成
如果你只做这两件事,你只会在非常特定的地方等待,而不是到处都需要它们(减少调试时的复杂性和混乱等)。