java - 将 isExists 函数添加到 WebElement
问题描述
我想扩展 selenium 并实现这样的东西:
public class IsExistsWebElement extends WebElement {
public boolean isExists() {
try {
this.getText();
return true;
} catch (NoSuchElementException e) {
return false;
}
}
}
然后像这样使用它(使用页面工厂):
public class HomePage{
@FindBy(class = "button")
private IsExistsWebElement button;
public HomePage(WebDriver driver) {
PageFactory.initElements(driver, this);
}
public boolean isButtonExists() {
return this.button.isExists();
}
}
实现这样的事情的最佳方法是什么?
解决方案
如果您正在寻找自定义实现,那么您必须在 selenium 之上创建一个新框架,并且必须为大多数事情编写自己的实现。
例如RemoteWebElement
类实现了WebElement
接口。但是仅仅在代码下面编写并像我们为 WebElement 所做的那样具有访问权限并不简单
例如IsExistsWebElement element = driver.findElement(By.id("a"));
class IsExistsWebElement extends RemoteWebElement {
public boolean isExists() {
try {
this.getText();
return true;
} catch (NoSuchElementException e) {
return false;
}
}
}
如果您正在寻找基于 selenium 的新框架并且能够负担得起时间(可能是 3、6、9 .. 个月,取决于资源)和成本,那么请愉快地去争取。
或者
然后在页面对象模型中寻找以通用方式管理等待
- 创建一个 BasePage 类
- 在构造函数中启动显式等待
- 为存在、可见性等创建等待方法
- 在您的其他页面类中扩展此 BasePage 类
例如
public BasePage(WebDriver driver) {
this.driver = driver;
wait = new WebDriverWait(driver, TIMEOUT, POLLING);
PageFactory.initElements(new AjaxElementLocatorFactory(driver, TIMEOUT), this);
}
public void waitForElementReady(WebElement element) {
try {
wait.until(ExpectedConditions.visibilityOf(element));
} catch (TimeoutException exception) {
System.out.println("Element didn't find in given time");
}
}
推荐阅读
- reactjs - 在危险地反应SetInnerHTML中将json显示为html
- r - 在 TOC 之前将代码添加到 Bookdown gitbook 模板
- swift - Xcode 搜索栏对更改文本或取消单击没有反应
- wordpress - Wordpress 清除页面模板的模板缓存?
- linux - Git克隆/从Windows拉到本地网络中的树莓派
- laravel - 我认为可以分解的控制器逻辑中的分解辅助
- python - ValueError:形状 (None, 9) 和 (None, 10) 不兼容
- python - cmake 无法在 conda 环境中找到 boost python
- c# - 跟踪、调试和信息消息未从 WorkerService 到达 App Insights
- haskell - 围绕 IO 创建一个包装器 Monad