Selenium定位不到元素的解决方法—iframe挡住了去路

发表于:2013-12-31 11:24

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

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

  刚接触Selenium,在调试过程中发现有些元素定位不到,于是求助了百度,查找到的资料是这么说的:如果需要定位的元素在某个frame里,则单独通过id/name/xpath是定位不到此元素的。比如,原本想通过WebElement element=driver.FindElement(By.LinkText("XXX"));来定位元素的,但由于该元素在iframe. id="left_frame"这个frame里面,所以需要先定位frame,WebElement element=driver.SwitchTo().Frame("left_frame").FindElement(By.LinkText("XXX"));
  此外还有个问题,就是相关的操作是在不同的frame中定位元素的。比如,先在left_frame中定位元素Id=TestFor1,然后在right_frame中定位元素Id=TestFor2。这种情况下,先切到left_frame,driver.SwitchTo().Frame("left_frame");再定位元素TestFor1,driver.FindElement(By.Id("TestFor1"));再切到默认的content,driver.SwitchTo().DefaultContent();再切到right_frame,driver.SwitchTo().Frame("right_frame");再定位元素TestFor2,driver.FindElement(By.Id("TestFor2"));
  在实际应用中,该方法能解决元素无法定位的问题,写了个C#通用接口(不管元素是否在frame里面),如下:
  publicIWebElementGetElement(stringstrDefined,boolbFrame.=false)
  {
  try
  {
  // 如果元素不在frame中,则切到默认的content
  if(!bFrame)
  {
  _webDriver.SwitchTo().DefaultContent();
  }
  IWebElementele=null;
  stringstrFrame.=m_cc.GetElementFrame(strDefined);
  // 如果元素在frame里,先切到frame
  if(null!=strFrame.&&""!=strFrame)
  {
  IWebElementFrameEle=GetElement(strFrame,true);
  _webDriver.SwitchTo().Frame(FrameEle);
  }
  stringstrID=m_cc.GetElementID(strDefined);
  // 如果元素的ID为空,则通过XPath来定位元素
  if(""==strID)
  {
  stringstrXPath=m_cc.GetElementXPath(strDefined);
  else=_webDriver.FindElement(By.XPath(strXPath));
  }
  else
  }
  }
版权声明:本文出自 xiaobaiwdn 的51Testing软件测试博客:http://www.51testing.com/?367232
原创作品,转载时请务必以超链接形式标明本文原始出处、作者信息和本声明,否则将追究法律责任。
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

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

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

沪ICP备05003035号

沪公网安备 31010102002173号