硒2-将焦点切换到没有名称/ID的框架
-
30-09-2019 - |
题
因此,现在我试图弄清楚当框架没有名称或ID时,如何将焦点切换到Selenium 2中的框架?对于一个指定的框架,我做:
driver.SwitchTo().Frame(FrameName);
但是什么没有名字?有人有这个经验吗?
解决方案
driver.switchto.frame()是 超载以接受框架名称或整数. 。此INT是可用框架的0基于0的索引。第一帧将是0,第二个1等。
我刚刚使用Java绑定和Firefox对此HTML页面进行了非常快速的测试。
<html>
<frameset rows="50%,50%">
<frame src="frame_a.htm" />
<frame src="frame_b.htm" />
</frameset>
</html>
我成功地使用驱动程序。Switchto()。帧(0);请参考帧和驱动程序。Switchto()。帧(1);访问框架b。
其他提示
您可以使用框架的索引。由于您没有框架的名称和ID
在Selenium中,如果您知道框架的相对位置应该能够使用selectframe命令与字符串“相对= up”将其移动到帧上 selenium.SelectFrame("relative=up");
或跳到顶帧使用“相对= top”
您只需提供IFRAME而不是Iframe-name的ID即可。
请参阅我的下面示例,对我有用。
在示例中,我要切换到我的页面中的一个iframe,然后单击该iframe中的元素,即“ worksheet0”。
使用代码:
driver.switchTo().frame("topframe");
WebElement worksheet0 = driver.findElement(By.xpath("//*@id='reportSelect:Worksheet_lbl']")); worksheet0.click();
iframe的html:
< iframe id="topframe" height="83px" frameborder="0" width="100%" scrolling="NO" '1331808552380'"="" +="" src="initialize.do?init=header&cacheBuster=" name="topframe" marginheight="0" marginwidth="0">
除了使用索引(正如其他答案所暗示的那样) C# 您可以通过tagName选择iframe。我的示例假设页面上只有一个和只有一个iframe。
try
{
var iFrameElement = Driver.FindElementByTagName("iFrame");
var driver = Driver.SwitchTo().Frame(this.iFrameElement);
var element = driver.FindElement(selector);
// do what you need with the element
}
finally
{
// don't forget to switch back to the DefaultContent
Driver.SwitchTo().DefaultContent();
}
注意:例如,您必须从iWebelement .Text或.click中获取信息,例如拨打driver.switchto()。defaultContent();
我创建了这些扩展方法来帮助
public static IWebDriver SwitchToIFrame(this RemoteWebDriver driver)
{
// http://computerrecipes.wordpress.com/2012/08/23/selenium-webdriver-interact-with-an-element-inside-an-iframe/
// http://stackoverflow.com/questions/3549584/selenium-2-switching-focus-to-a-frame-that-has-no-name-id
var iFrameElement = driver.FindElementByTagName("iFrame");
return driver.SwitchTo().Frame(iFrameElement);
}
public static void SwitchOutOfIFrame(this IWebDriver driver)
{
driver.SwitchTo().DefaultContent();
}
使用扩展方法的示例:
public void ClickPrintButton()
{
var iFrameDriver = Browser.Driver.SwitchToIFrame();
try
{
iFrameDriver.FindElement(By.Id("saveButton")).Click();
}
finally
{
Browser.Driver.SwitchOutOfIFrame();
}
}
不隶属于 StackOverflow