Webdriver定位不到元素的解决办法

发表于:2014-12-09 10:42

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:passionboyxie    来源:51Testing软件测试网采编

  不知道怎么回事,先前能跑动的case,现在元素始终找不到。
  但是我xpath是能定位得到的,debug了一下,结果发现在
  WebElementelement = locator.findElement();就卡住了。
  弄了好久也没有成功。
  网上找例子:
  Selenium2(WebDriver)_如何判断WebElement元素对象是否存在
  1.selenium中如果去寻找元素,而元素不存在的话,通常会抛出NoSuchElementException 导致测试失败,但有时候,我们需要去确保页面元素不存在,才是我们正确的验收条件下面的方法可以用来判定页面元素是否存在
    1 public boolean doesWebElementExist(WebDriver driver, By selector)
    2{
    3
    4         try
    5         {
    6                driver.findElement(selector);
    7                returntrue;
    8        }
    9        catch(NoSuchElementException e)
    10         {
    11                 return false;
    12         }
    13 }
  2.一般有这样的应用场合,例如我们要验证在一个网站是否登录成功,那么可以通过判断登录之后是否显示相应元素:
  WebElementlinkUsername =driver.findElement(By.xpath("//a[contains(text(),"+username+")]"));
  return linkUsername.isDisplayed();
  这一方法的前提是:该元素之前已经存在,仅仅需要判断是否被显示。
  现在存在另一种场合,页面元素并不存在,即通过driver.findElement只能在超时之后得到NoSuchElementException的异常。
  因此只好通过如下方法解决:
1 boolean ElementExist (ByLocator )
2{
3 try
4 {
5 driver.findElement( Locator );
6 returntrue;
7}
8 catch(org.openqa.selenium.NoSuchElementException ex)
9{
10     returnfalse;
11 }
12 }
  但这一方法仍然不理想,有这样两个问题:
  1、这一方法不属于任何一个page页,因此需要额外进行框架上的变更以支持这些功能函数,否则就必须在每一个用到该函数的page类写一遍。
  2、仍然需要等到超时才能得知结果,当需要频繁使用该函数的时候会造成相当的时间浪费。
  3.
  类似于seleniumRC中的isTextPresent方法
  用xpath匹配所有元素(//*[contains(.,'keyword')]),判断是否存在包含期望关键字的元素。
  使用时可以根据需要调整参数和返回值。
1 public boolean isContentAppeared(WebDriver driver,String content) {
2       booleanstatus = 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 }
  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 }
  然后又看了一篇文章
  selenium webdriver定位不到元素的五种原因及解决办法
  1.动态id定位不到元素
  for example:
  //WebElement xiexin_element = driver.findElement(By.id("_mail_component_82_82"));
  WebElement xiexin_element = driver.findElement(By.xpath("//span[contains(.,'写  信')]"));
  xiexin_element.click();
  上面一段代码注释掉的部分为通过id定位element的,但是此id“_mail_component_82_82”后面的数字会随着你每次登陆而变化,此时就无法通过id准确定位到element。
  所以推荐使用xpath的相对路径方法查找到该元素。
21/212>
《2023软件测试行业现状调查报告》独家发布~

精彩评论

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号