我在发现结果元素可见或不可见的地方编写了一个代码,但是我收到了异常。
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
我不确定我在哪里出错?
为了避免异常,并且昂贵地使用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");
要么使用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");
}
由于您不期望该元素存在,因此以下代码将引发异常:
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 })
这是硒的问题,您需要使用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
}
让我这样说:IsDisplayed
将对类型为WebElement
的对象起作用。
这里是澄清
findElement不应用于查找不存在的元素,而应使用findElements(By)并声明零长度响应。
在findElement上找到