多测师是一家拥有先进的教学理念,强大的师资团队,业内好评甚多的接口自动化测试培训机构!

17727591462

联系电话

您现在所在位置:接口自动化测试培训 > 新闻资讯

selenium webdriver定位不到元素的五种原因及解决办法

更新时间:2022-05-06 09:15:06 作者:多测师 浏览:230

  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的相对路径方法查找到该元素。

selenium webdriver定位不到元素的五种原因及解决办法

  2.iframe原因定位不到元素

  由于需要定位的元素在某一个frame里边,所以有时通过单独的id/name/xpath还是定位不到此元素

  比如以下一段xml源文件:

<iframe id="left_frame" scrolling="auto" frameborder="0" src="index.php?m=Index&a=Menu" name="left_frame" noresize="noresize" style="height: 100%;visibility: inherit; width: 100%;z-index: 1">

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<body class="menuBg">

<div id="menu_node_type_0">

<table width="193" cellspacing="0" cellpadding="0" border="0">

<tbody>

<tr>

<tr>

<td id="c_1">

<table class="menuSub" cellspacing="0" cellpadding="0" border="0" align="center">

<tbody>

<tr class="sub_menu">

<td>

<a href="index.php?m=Coupon&a=SearchCouponInfo" target="right_frame">密码重置</a>

</td>

</tr>

  原本可以通过

  WebElement element = driver.findElement(By.linkText("密码重置"));

  来定位此元素,但是由于该元素在iframe id="left_frame"这个frame里边  所以需要先通过定位frame然后再定位frame里边的某一个元素的方法定位此元素

  WebElement element =driver.switchTo().frame("left_frame").findElement(By.linkText("密码重置"));

  3.不在同一个frame里边查找元素

  大家可能会遇到页面左边一栏属于left_frame,右侧属于right_frame的情况,此时如果当前处在left_frame,就无法通过id定位到right_frame的元素。此时需要通过以下语句切换到默认的contentdriver.switchTo().defaultContent();

  例如当前所在的frame为left_frameWebElement xiaoshoumingxi_element = driver.switchTo().frame("left_frame").findElement(By.linkText("销售明细"));

  xiaoshoumingxi_element.click();

  需要切换到right_frame

  driver.switchTo().defaultContent();

  Select quanzhong_select2 = new Select(driver.switchTo().frame("right_frame").findElement(By.id("coupon_type_str")));

  quanzhong_select2.selectByVisibleText("售后0小时");

  4.  xpath描述错误

  这个是因为在描述路径的时候没有按照xpath的规则来写 造成找不到元素的情况出现

  5.点击速度过快  页面没有加载出来就需要点击页面上的元素

  这个需要增加一定等待时间,显示等待时间可以通过WebDriverWait 和util来实现

  例如:

  //用WebDriverWait和until实现显示等待 等待欢迎页的图片出现再进行其他操作

  WebDriverWait wait = (new WebDriverWait(driver,10));

  wait.until(new ExpectedCondition<Boolean>(){

  public Boolean apply(WebDriver d){

  boolean loadcomplete = d.switchTo().frame("right_frame").findElement(By.xpath("//center/div[@class='welco']/img")).isDisplayed();

  return loadcomplete;

  }

  });

  也可以自己预估时间通过Thread.sleep(5000);//等待5秒 这个是强制线程休息。

  以上内容为大家介绍了自动化测试中的selenium webdriver定位不到元素的五种原因及解决办法,本文由多测师亲自撰写,希望对大家有所帮助。了解更多自动化测试相关知识:https://www.aichudan.com/xwzx/

联系电话

17727591462

返回顶部