【问题标题】:How to handle Selenium findElements while elements is not present in html taghtml标签中不存在元素时如何处理Selenium findElements
【发布时间】:2021-04-03 22:30:08
【问题描述】:

在用户界面中 如果输入的文本无效,则会在 UI 和 HTML 代码中显示错误元素/标签

<div _ngcasde-ltw-c3="" class="error"> Organization only contain alpha chars or special chars -,. </div>

如果输入有效文本,则 UI 和 HTML 代码中不会显示错误元素/标签,

No error in HTML tag

所以在编写 selenium webDriver 代码时,我添加了下面的代码,它在 HTML 代码中出错(无效文本场景)但 HTML 代码中没有错误标记(有效文本场景)时工作,我的执行卡在代码行下方(元素或计数或结果)并且不再继续。它仍然显示在该行中无限时间运行的执行

WebElement xyz = driver.findElement(By.className("modal-body"));

List<WebElement> elements = xyz.findElements(By.xpath("//div[@class='error']"));
OR
int count = xyz.findElements(By.xpath("//div[@class='error']")).size();
OR
boolean result = xyz.findElement(By.xpath("//div[@class='error']")).isDisplayed();

所以请让我知道如何处理这个问题并继续进行,如果元素不存在,那么它应该返回大小 0 或结果为 false

基于此输出,我将使用 if 子句打印消息,如果大小不为零则错误,如果大小为 0 则成功

【问题讨论】:

  • 现在有什么问题

标签: java html selenium


【解决方案1】:

使用 FindBy 注释声明您的错误元素,并仅在页面上生成错误时使用它。

@FindBy(id = "foobar") WebElement foobar;

示例:

@FindBy(id = "error_css") WebElement errorElement;

public void verifyError(){
    // Click on Save button without filling out mandatory fields on the form
    save.click();
    // Now validate error as it will be generate on the HTML 
    errorElement.gettext();   
}

测试愉快:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-30
    • 2019-11-02
    • 1970-01-01
    • 2017-03-07
    • 2017-08-07
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    相关资源
    最近更新 更多