Selenium2(WebDriver)_如何判断WebElement元素对象是否存在

1. selenium中如果去寻找元素,而元素不存在的话,通常会抛出NoSuchElementException 导致测试失败,但有时候,我们需要去确保页面元素不存在,才是我们正确的验收条件下面的方法可以用来判定页面元素是否存在

 1 public boolean doesWebElementExist(WebDriver driver, By selector)
 2 { 
 3 
 4         try 
 5         { 
 6                driver.findElement(selector); 
 7                return true; 
 8         } 
 9         catch (NoSuchElementException e) 
10         { 
11                 return false; 
12         } 
13 }         

 

2.一般有这样的应用场合,例如我们要验证在一个网站是否登录成功,那么可以通过判断登录之后是否显示相应元素: 

WebElement linkUsername = driver.findElement(By.xpath("//a[contains(text(),"+username+")]"));

return linkUsername.isDisplayed();
 
这一方法的前提是:该元素之前已经存在,仅仅需要判断是否被显示。
 
现在存在另一种场合,页面元素并不存在,即通过driver.findElement只能在超时之后得到NoSuchElementException的异常。
 
因此只好通过如下方法解决:
 1 boolean ElementExist (By Locator )
 2 {
 3   try
 4   {
 5     driver.findElement( Locator );
 6     return true;
 7   }
 8   catch(org.openqa.selenium.NoSuchElementException ex)
 9   {
10       return false;
11   }
12 }

 但这一方法仍然不理想,有这样两个问题: 

1、这一方法不属于任何一个page页,因此需要额外进行框架上的变更以支持这些功能函数,否则就必须在每一个用到该函数的page类写一遍。 
2、仍然需要等到超时才能得知结果,当需要频繁使用该函数的时候会造成相当的时间浪费。
 
3.
类似于seleniumRC中的isTextPresent 方法 
用xpath匹配所有元素(//*[contains(.,'keyword')]),判断是否存在包含期望关键字的元素。 
使用时可以根据需要调整参数和返回值。 
 1 public boolean isContentAppeared(WebDriver driver,String content) {  
 2       boolean status = false;  
 3       try {  
 4           driver.findElement(By.xpath("//*[contains(.,'" + content + "')]"));  
 5           System.out.println(content + " is appeard!");  
 6           status = true;  
 7       } catch (NoSuchElementException e) {  
 8           status = false;  
 9           System.out.println("'" + content + "' doesn't exist!"));  
10      }  
11      return status;  
12  }  

详细xpath介绍请见:http://www.w3school.com.cn/xpath/

  
4. Xpath 多重判断 
1 while(currentPageLinkNumber<MaxPage)
2 {
3   WebElement PageLink;
4   PageLink = driver.findElement(By.xpath("//a[@class = 'PageLink' and @title ='"+Integer.toString(currentPageLinkNumber+1)+"']"));
5   PageLink.click();
6   currentPageLinkNumber++;
7 //OtherOperation();
8 }

 

 
 
转自:http://blog.csdn.net/aerchi/article/details/8057544
 
posted @ 2013-12-25 16:30  贺满  阅读(54376)  评论(0编辑  收藏  举报