2016-08-25 64 views
1

我在某些特定情况下遇到了一些困难。当div被隐藏时无法找到元素

当没有错误时,页面如下所示。

<script src="includes/js/errorHandling.js?v=5" type="text/javascript"/> 
<div class="pmo_title"> 
<!--end pmo title--> 
<div class="spacer2"/> 
<div class="pmo-container"> 

但是,如果发生任何错误显示额外的div类。

<script src="includes/js/errorHandling.js?v=5" type="text/javascript"/> 
<div class="pmo_title"> 
<!--end pmo title--> 
<div class="pmo_warning"> 
<div class="pmo-container"> 
<span class="message_title">Errors :</span> 
<!--display first item of list with no comma--> 
<span id="fileError" class="error">File to Upload required</span> 
</div> 
</div> 
<div class="spacer2"/> 
<div class="pmo-container"> 

我想验证我是否上传了一个无效文件,并显示错误抛出异常,否则继续。

我写了下面的代码

@FindBy(xpath = "//div[@class='pmo_warning']") 
private WebElement errorMessage; 
if (errorMessage !=null){ 
throw (new IOException("file not found")); 

    } 

return initialize(driver, FileUpload.class); 

它抛出异常的有效和无效输入

我也曾尝试

@FindBy(xpath = "//div[@class='pmo_warning']") 
private WebElement errorMessage; 
if (errorMessage.IsDisplayed()){ 
throw (new IOException("file not found")); 

    } 

return initialize(driver, FileUpload.class); 

对于文件没有错误时显示:

无法罗列美食元素

回答

1

你应该尝试使用@FindAll获得清单WebElement改为检查其大小如下: -

@FindAll(@FindBy(how = How.CSS, using = "div.pmo_warning")) 
List<WebElement> errorMessage; 

if (errorMessage.size() > 0 && errorMessage.get(0).isDisplayed()){ 
    throw (new IOException("file not found")); 
} 
return initialize(driver, FileUpload.class); 
+0

谢谢它的作品。唯一的问题是Find all会增加等待时间。 – user2410266

+0

为什么只需要一个FindBy的FindAll注解? FindAll为列表中提到的所有FindBy提供OR运算符。看看这个 - http://stackoverflow.com/questions/25914156/difference-between-findall-and-findbys-annotations-in-webdriver-page-factory。您可以删除FindAll,只需使用带有单个FindBy批注的列表声明。 – Grasshopper

+0

@Grasshopper FindBy只是返回单个WebElement,可以用FindAllBy代替'@FindAllBy(how = How.CSS,using =“div.pmo_warning”)列表 errorMessage' ..感谢指出...... :) –

3

driver.findElements(By.xpath( “// DIV [@类= 'pmo_warning']”))。大小()!= 0