【问题标题】:How to continue a script when web elements are not present in the page当页面中不存在 Web 元素时如何继续执行脚本
【发布时间】:2020-05-20 05:27:45
【问题描述】:

我正在尝试从下拉列表中选择一个选项。如果没有可见的下拉选项,则应继续执行脚本。

请在下面找到我的代码 -

List<WebElement> drop_down_options = driver.findElements(By.className("mat-option"));
if (drop_down_options.size() == 0) {
    System.out.println("drop down options are not visible");
} else {
   drop_down_options.get(0).click();
}

这里如果没有下拉选项,执行脚本需要很长时间。在我的网页中,某些下拉菜单被禁用(具有默认值),因此我不想单击或选择该选项。

但它在我上面提到的代码的第一行停留了一段时间(超过 4 分钟)。

即使有元素是不可见的,它也会等待一段时间,所以我的脚本需要时间来执行。

我试过了

  1. isDisplayed(), isEnabled(),isPresent

  2. 尝试捕捉

如果页面中没有可见的元素,请给我一个解决方案以继续我的脚本

更新评论:

我已经尝试了下面提到的所有解决方案

1.在第一个选项中选择 select = new Select(drop_down_options);显示错误说“将参数 drop_down_options 转换为 WebElement”

2.where 与第二个选项一样,getText() 返回输入字段附近的占位符值和其他帮助文本消息 GetAttribute() 返回 null

  1. 尝试使用以下代码,但结果相同,如果没有选项则需要时间来执行

        for (int d = 0; d < dropdowns.size(); d++) {
    
    
                Thread.sleep(1000);
    
                System.out.println("----------------" +dropdowns.get(d).getAttribute("value"));
                System.out.println("----------------" +dropdowns.get(d).getText());
    
    
                    dropdowns.get(d).click();
    
                    Thread.sleep(1000);
    
                    WebDriverWait wait=new WebDriverWait(driver,10);
    
             wait.until(ExpectedConditions.visibilityOfAllElements(drop_down_options));
    
             try{
    
                    if (drop_down_options.size()==0) {
    
                        drop_down_options.get(0).click();
    
    
                    }
                }catch(Exception e)
                {
    
                e.printStackTrace();
    
                }
    

【问题讨论】:

  • 必须等待(隐式和显式)导致问题。类名mat-option 在您的页面中是唯一的吗?
  • 是的 mat-option 在我的页面中是唯一的,我的动态网页中有不同类型的输入属性,所以我尝试使用类名迭代这些字段。

标签: java selenium selenium-webdriver automated-tests testng


【解决方案1】:

如果您的 DOM 使用选项标签作为下拉菜单,请尝试以下操作:

List<WebElement> drop_down_options = driver.findElements(By.className("mat-option"));// Assuming class name is from parent tag.
Select select = new Select(drop_down_options);
List<WebElement> allOptions = select.getOptions();

选项 2

  • 尝试使用 gettext() 或 getattribute() 获取下拉菜单的默认值

  • 你可以检查属性值为 =="DISABLE" 不要点击。

  • 或者你可以获取默认值并检查它是否不为空然后只执行点击操作

选项 3

  • try and catch {} 如果不工作,它应该可以工作,把你的工作和细节。注释 Catch 不应该有返回语句在您的异常之后继续。

【讨论】:

  • 我已经尝试了所有三种解决方案,请在上面找到更新的 cmets
  • 你能分享你的网址吗?可能你需要检查你的 xpath。
猜你喜欢
  • 1970-01-01
  • 2021-12-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多