【问题标题】:How to write code if not an element exists in selenium [JAVA]如果硒中不存在元素,如何编写代码[JAVA]
【发布时间】:2019-12-24 10:20:04
【问题描述】:

这是一个登录测试场景。 有两个用户。他们是有效用户和无效用户。 弹出确定点击正在测试中。

问题 ----->

如果---->(如果不存在元素)---- print("成功登录"),

else ----> (如果元素存在) ----- 弹出确定点击。与其他用户一起登录。

没有这样的元素情况,我不能这样做。

错误

 Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"html/body/div/div/div[3]/button[1]"}
  (Session info: chrome=79.0.3945.88)

代码

    WebElement temp444 = driver.findElement(By.xpath("html/body/div/div/div[3]/button[1]"));
    System.out.println(temp444.getSize());
    if(temp.getSize()!=null){

         temp.click(); // ----> It's working!

    }
    else {

    System.out.println("good working"); // ----> It isn't working.

    }

【问题讨论】:

    标签: java html selenium testing


    【解决方案1】:

    使用 findElements() 返回元素列表,然后检查列表的大小,如果大于 0 表示按钮存在并单击它。

    List<WebElement> elements = driver.findElements(By.xpath("html/body/div/div/div[3]/button[1]"));
            System.out.println(elements.size());
            if(elements.size()>0)
            {
    
                elements.get(0).click();
    
            }
            else {
    
            System.out.println("good working"); 
    
            }
    

    【讨论】:

      【解决方案2】:

      尝试使用 driver.findElements 而不是 driver.findElement

      在这种情况下如果元素不存在 temp.getSize() == 0

      【讨论】:

        【解决方案3】:
        1. 您可以使用 try catch 块代替 if/else 块,类似于 下面的代码

          试试

          {

          driver.findElement(By.xpath("html/body/div/div/div[3]/button[1]"));
          

          }

          catch(NoSuchElementException)

          {

          Console.WriteLine("Element does not exist!");
          

          }

        2. 您还可以找到是否存在这样的元素。

          Boolean isPresent = driver.findElements(By.yourLocator).size() > 0

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-01-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-02
          • 1970-01-01
          • 2021-06-08
          相关资源
          最近更新 更多