You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Selenium(C#)中递归定位嵌套iframe内的元素?

问题描述

我找到了两个关于递归查找嵌套iframe元素的相关话题,但它们都不是基于Selenium和C#的。以下是我当前实现的代码:

public static IWebElement FindWebElementByXPath(ChromeDriver chromeDriver, string xPath, string frameType = "iframe")
{
    Console.WriteLine("         Searching for Element: " + xPath + "\n");
    Console.WriteLine();

    IWebElement element;
    try
    {
        chromeDriver.SwitchTo().DefaultContent();
        element = chromeDriver.FindElement(By.XPath(xPath));
        if (element != null)
        {
            Console.WriteLine("     Found Element: " + xPath + " (" + element.Text + ")\n");
            Console.WriteLine();
            return element;
        }

    }
    catch (Exception)
    {
        // ignored
    }

    var windowHandles = chromeDriver.WindowHandles;

    foreach (var window in windowHandles)
    {

        chromeDriver.SwitchTo().Window(window);

        var frames = chromeDriver.FindElements(By.TagName(frameType));

        foreach (var frame in frames)
        {
            chromeDriver.SwitchTo().DefaultContent();
            chromeDriver.SwitchTo().Frame(frame);
            try
            {
                element = chromeDriver.FindElement(By.XPath(xPath));
                if (element != null)
                {
                    Console.WriteLine("     Found Element: " + xPath + " (" + element.Text + ")\n");
                    Console.WriteLine();
                    return element;
                }
            }
            catch (Exception)
            {
                // ignored
            }


            var frameChildren = chromeDriver.FindElements(By.TagName(frameType));
            foreach (var child in frameChildren)
            {
                chromeDriver.SwitchTo().DefaultContent();
                chromeDriver.SwitchTo().Frame(frame);
                chromeDriver.SwitchTo().Frame(child);

                try
                {
                    element = chromeDriver.FindElement(By.XPath(xPath));
                    if (element != null)
                    {
                        Console.WriteLine("     Found Element: " + xPath + " (" + element.Text + ")\n");
                        Console.WriteLine();
                        return element;
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }
        }
    }

    Console.WriteLine("Failed to find Element: " + xPath + "\n");
    Console.WriteLine();
    return null;
}

目前这段代码仅能处理一级iframe及其子iframe,无法应对更深层级的嵌套结构,我不清楚如何编写递归函数来遍历所有层级的iframe。


内容的提问来源于stack exchange,提问作者Avrigeanu Laurian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 03:24:23