Selenium 2 - Switching focus to a frame that has no name/id

后端 未结 5 1994
轻奢々
轻奢々 2021-01-02 12:13

So right now I\'m trying to figure out how I can switch focus to a frame in Selenium 2 when the frame has no name or id? For a named frame I do:

driver.Switc         


        
5条回答
  •  旧时难觅i
    2021-01-02 12:41

    In addition to using the index (as the other answers suggest), in C# you can select the iFrame by tagName. My example assumes there is one and only one iFrame on the page.

    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();
    }
    

    Note: You have to get the information from the IWebElement .Text or .Click for example, before calling Driver.SwitchTo().DefaultContent();

    I created these extensions methods to help

    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();
    }
    

    An example of using the extensions methods:

    public void ClickPrintButton()
    {
        var iFrameDriver = Browser.Driver.SwitchToIFrame();
        try
        {
            iFrameDriver.FindElement(By.Id("saveButton")).Click();
        }
        finally
        {
            Browser.Driver.SwitchOutOfIFrame();
        }
    }
    

提交回复
热议问题