Selenium-例外,而不是布尔值

问题描述 投票:1回答:5

我在发现结果元素可见或不可见的地方编写了一个代码,但是我收到了异常。

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":".//*[@class='airbnb-wide-block-search-btn js-airbnb-search-btn']"}

这是我的代码

wd.navigate().refresh();
Thread.sleep(7000);
boolean airbnb = wd.findElement(By.xpath(".//*[@class='airbnb-wide-block-search-btn js-airbnb-search-btn']")).isDisplayed();
assertFalse(airbnb, "Airbnb Add will not show After clicking Add one times");

有没有建议为什么找不到元素?如果找不到元素,则应该为false我不确定我在哪里出错?

java selenium selenium-webdriver
5个回答
3
投票

为了避免异常,并且昂贵地使用try - catch,您可以使用findElements定位元素。如果结果列表不为空,则可以检查是否显示现有元素

List<WebElement> elements = wd.findElements(By.xpath(".//*[@class='airbnb-wide-block-search-btn js-airbnb-search-btn']"));
assertFalse(elements.size() > 0 && elements.get(0).isDisplayed(), "Airbnb Add will not show After clicking Add one times");

1
投票

要么使用try- catch块,要么使用throws异常来捕获NoSuchElementException

public void methodName() throws Exception
{
    if(wd.findElement(By.xpath(".//*[@class='airbnb-wide-block-search-btn js-airbnb-search-btn']")).isDisplayed())
{
  System.out.println("Element displayed");
} 
}

try
{
if(wd.findElement(By.xpath(".//*[@class='airbnb-wide-block-search-btn js-airbnb-search-btn']")).isDisplayed())
{
  System.out.println("Element displayed");
} 
}

catch(NoSuchElementException e)
{
  System.out.println("Element is not displayed");
}

0
投票

由于您不期望该元素存在,因此以下代码将引发异常:

boolean airbnb = wd.findElement(By.xpath(".//*[@class='airbnb-wide-block-search-btn js-airbnb-search-btn']")).isDisplayed();

甚至您的assert语句也不会到达。

您实际上可以在代码中放置预期的异常,而不是在Junit中声明为:

@Test(expected = NoSuchElementException.class)
public void youtTest() {
   // do whatever you're doing
   Thread.sleep(7000);
   wd.findElement(By.xpath(".//*[@class='airbnb-wide-block-search-btn js-airbnb-search-btn']"));
}

TestNG中,语法有点像:

@Test(expectedExceptions = { NoSuchElementException.class })

0
投票

这是硒的问题,您需要使用try catch块,如下所示

try
{

        if(wd.findElement(By.xpath(".//*[@class='airbnb-wide-block-search-btn js-airbnb-search-btn']")).isDisplayed())
  {
        //Your code
  }
}
catch (Exception e)
{
        //Your code
}

0
投票

让我这样说:IsDisplayed将对类型为WebElement的对象起作用。

这里是澄清

findElement不应用于查找不存在的元素,而应使用findElements(By)并声明零长度响应。

findElement上找到

© www.soinside.com 2019 - 2024. All rights reserved.