http://www.cnblogs.com/puresoul/archive/2013/12/25/3490909.html
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+")]"));
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 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 }
Selenium2(WebDriver)_如何判断WebElement元素对象是否存在
原文:http://www.cnblogs.com/donaldlee2008/p/5264178.html