代码之家  ›  专栏  ›  技术社区  ›  James

Selenium 2-将焦点切换到没有名称/id的帧

  •  8
  • James  · 技术社区  · 14 年前

    所以现在我想弄清楚,在Selenium 2中,当一个帧没有名称或id时,如何将焦点切换到该帧?对于命名帧,我执行以下操作:

    driver.SwitchTo().Frame(FrameName);
    

    但什么是没有名字?有人有过这样的经历吗?

    5 回复  |  直到 14 年前
        1
  •  11
  •   pnewhook    14 年前

    驱动程序.switchTo.frame()是 overloaded to accept a frame name or an integer

    <html>
    <frameset rows="50%,50%">
        <frame src="frame_a.htm" />
        <frame src="frame_b.htm" />
    </frameset>
    </html>
    

    我成功地使用了驱动程序.switchTo()。帧(0);参考帧a和 驱动程序.switchTo()。帧(1);访问帧b。

        2
  •  1
  •   nilesh    14 年前

    驱动程序.switchTo().帧(int frameIndex)

        3
  •  0
  •   Nathan    14 年前

    在selenium中,如果您知道帧的相对位置,您应该能够使用带有字符串“relative=up”的selectFrame命令将其向上移动一帧。 selenium.SelectFrame("relative=up");

        4
  •  0
  •   Rakesh Prabhakaran    13 年前

    您可以只提供iframe的id而不是iframe名称。

    请看我下面的例子,它为我工作。
    在本例中,我切换到页面中的一个iframe,并单击该iframe中的元素“worksheet0”。

    使用代码:

    driver.switchTo().frame("topframe");    
        WebElement worksheet0 = driver.findElement(By.xpath("//*@id='reportSelect:Worksheet_lbl']"));               worksheet0.click();             
    

      < iframe id="topframe" height="83px" frameborder="0" width="100%" scrolling="NO" '1331808552380'"="" +="" src="initialize.do?init=header&cacheBuster=" name="topframe" marginheight="0" marginwidth="0">
    
        5
  •  0
  •   AlignedDev    11 年前

    除了使用索引(如其他答案所示),在 C级# 您可以选择iFrame by标记名。我的示例假设页面上只有一个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获取信息驱动程序.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();
        }
    }