无法使用SeleniumJava访问框架内的元素



我正在使用selenium来测试网页。现在我正在测试一个包含框架的网页。我们遵循的结构。

<frameset title="Application Content">
<frame name="main" src="qweMain.jsp?language=ENG" scrolling="no" title="Main Frame">
#document
<html>
<head> </head>
<body>
<div>
<ou-button img="ico-menu" id="menuButton" usage="toolbar" onclick="main.doClose();main.onTopMenuClick('CI_MAINMENU', event);" title="Menu (Ctrl+Alt+M)" role="button" tabindex="5" aria-label="Menu (Ctrl+Alt+M)" onkeypress="onButtonKeyPress(event)"><svg class="icon-standard-container icon-size-standard icon-toolbar-container icon-size-toolbar" style=""><use xlink:href="ouaf/assets/svgs/ico-menu.svg#icon"></use></svg></ou-button>
</div>
</body>
</html>
</frame>
<noframes>
Browser not supported
</noframes>
</frameset>

我正在试着按菜单按钮。

driver.findElement(By.xpath("//ou-button[@img='ico-menu']")).click();

但我得到NoSuchElementException正在发生。我在寻找解决方案。所以我有了一些想法。一些开发人员建议在访问元素之前切换框架。我也试过了。

driver.switchTo().defaultContent();
new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("/html/frameset/frame")));
driver.switchTo().frame(driver.findElement(By.xpath("/html/frameset/frame")));

但我还是犯了同样的错误。请发表一些想法来解决这个问题。

所需的元素在<iframe>中,因此要与元素交互,您必须:

  • 诱导WebDriverWait等待所需的帧ToBeAvailableAndSwitchToIt
  • 诱导WebDriver等待所需的元素可点击
  • 您可以使用以下任一定位器策略:
    • 使用cssSelector:

      new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("frame[name='main'][title='Main Frame']")));
      new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("ou-button#menuButton[img='ico-menu'][title^='Menu'][aria-label^='Menu']"))).click();
      
    • 使用xpath

      new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//frame[@name='main' and @title='Main Frame']")));
      new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//ou-button[@id='menuButton' and @img='ico-menu'][starts-with(@title, 'Menu') and starts-with(@aria-label, 'Menu')]"))).click();
      

参考

你可以在中找到一些相关的讨论

  • 在SeleniumWebdriverJava中,是否可以在不使用driver.switchTo((.frame("frameName"(的情况下切换到框架中的元素
  • 硒:不能点击iframe中的按钮
  • NoSuchElementException,Selenium无法定位元素

您可以尝试使用带有javascript的单击或滚动到元素视图中。

var element = _driver.Driver.FindElement(Selector); var jsExecutor = (IJavaScriptExecutor)_driver.Driver; jsExecutor.ExecuteScript("arguments[0].scrollIntoView(true);", element); element.Click();

或者你可以尝试移动到元素并点击

var myElement = _driver.Driver.FindElement(Selector); var a = new Actions(_driver.Driver); a.MoveToElement(myElement).Click().Perform();

我不确定这些将如何处理iframe的工作,但希望这些可能会有所帮助。

您是否可以尝试使用以下代码切换到帧,该代码具有帧名称而不是xpath:

driver.switchTo().frame("main");

然后尝试点击想要的元素使用:

driver.findElement(By.xpath("//ou-button[@img='ico-menu']")).click();

您可以使用以下代码切换回主窗口:

driver.switchTo().defaultContent();

最新更新