2016-08-18 37 views
1

我使用的是Selenium Webdriver,我想在每一步之后打印一些消息,这样我就能够在成功时打印一些消息,但是在收到“无法定位元素”的故障时。请参阅我的代码:如何在Selenium webdriver中将“无法定位元素”更改为另一条消息,如“元素不存在”?

WebElement a= driver.findElement(By.xpath(".//*[@id='eviceSliderbuttonPrev']/a")); 

    if(a.isDisplayed()) 
    { 
     System.out.println("Device Slider button exists"); 

     a.click(); 

     System.out.println("Button is clickable"); 
    } 
    else { 
     System.out.println("Device Slider button doesn't exist!"); 

但其他条件不打印出来,当案件失败,我得到“无法定位元素”。

你知道如何解决这个问题吗?

回答

1

实际上findElement要么返回元素要么抛出NoSuchElementException,所以if(a.isDisplayed())条件只有在找到元素时才会遇到。

如果你想检查元素的存在,我建议尝试使用findElements代替,检查列表的大小,因为findElements总是返回要么是空列表或WebElement名单。

你应该尝试如下: -

List<WebElement> a= driver.findElements(By.xpath(".//*[@id='eviceSliderbuttonPrev']/a")); 

if(a.size() > 0 && a.get(0).isDisplayed()) 
{ 
    System.out.println("Device Slider button exists"); 
    a.get(0).click(); 
    System.out.println("Button is clickable"); 
}else { 
    System.out.println("Device Slider button doesn't exist!"); 
} 
+1

谢谢!这回答了我的问题..我是一个初学者和名单是什么对我而言是... 非常感谢你! – Zomzomzom

+1

你救了我的一周不仅我的一天:D谢谢你! – Zomzomzom

+0

@Zomzomzom没问题。很高兴帮助你..快乐学习... :) –

0

使用尝试捕捉:

try { 
    if(a.isDisplayed()) { 
     System.out.println("Device Slider button exists"); 
     a.click(); 
    } 
} catch(Exception e) { 
    System.out.println("Device Slider button doesn't exist!"); 
} 

你可以采取if条件,如果你想在上面的,但是这取决于你。该例外仍然在控制台中抛出,但是在这种情况下您正在控制它。

2

而不是isDisplayed()抛出一个NoSuchElementException而不是返回false,当元素不显示,您可以使用driver.findElements(...),它将返回一个列表。只需检查列表的大小为0或1而不是处理异常。

0

请注意,这个答案是一种替代方法来使用driver.findElements()方法。正如Moser在他的回答中所建议的那样,您可以使用try-catch。 但是,如果该元素不存在或未找到,并且程序将自行终止而不到达“try”块,则driver.findElement()方法将抛出NoSuchElementException。

因此,我们必须将driver.findElement()方法本身放在'try'块中。

try { 
    WebElement a= driver.findElement(By.xpath(".//*[@id='eviceSliderbuttonPrev']/a")); 
    // If above line throws NoSuchElementException, rest of the try block below will be skipped and you can print your desired message. 
    if (a != null) { // Element was present and found. 
     if(a.isDisplayed()) { 
      System.out.println("Device Slider button exists"); 
      a.click(); 
      System.out.println("Button is clickable"); 
     } 
    } 
} 
catch (org.openqa.selenium.NoSuchElementException) { 
    System.out.println("Device Slider button doesn't exist!"); 
} 
相关问题