C# Selenium Webdriver 在 Iframe 中查找元素

Mat*_*ttJ 5 c# iframe selenium-webdriver

我在寻找 iframe 时遇到问题。我想切换到此 iframe,然后单击其中的一个元素。

我尝试使用 Id、Xpath、TagName 和 CssSelector 查找 iframe,但每次查找元素时我的测试都会超时。

这是页面源代码中显示的 iframe:

<div xmlns="http://www.w3.org/1999/xhtml" id="dashboardView" style="display: block;">
        <iframe id="dashboardViewFrame" border="0" scrolling="no" frameborder="0"
style="visibility: visible; height: 607px; width: 1280px; background-color: transparent;"
src="HtmlViewer.ashx?Dd_ContentId=6a8a44ae-2bd5-4f3c-8583-e777279ad4f2"></iframe>
    </div>

<iframe xmlns="http://www.w3.org/1999/xhtml" id="dashboardViewFrame" border="0" scrolling="no"
frameborder="0" style="visibility: visible; height: 607px; width: 1280px; background-color:
transparent;" src="HtmlViewer.ashx?Dd_ContentId=6a8a44ae-2bd5-4f3c-8583-e777279ad4f2"></iframe>
Run Code Online (Sandbox Code Playgroud)

这是我当前的代码:

    public static bool IsAt
    {
        get
        {
            try
            {
                var dashboardiFrame = Driver.Instance.FindElement(By.Id("dashboardViewFrame"));
                //todo switch to iframe
                //todo find element within iframe
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

有人可以建议一种找到 iframe 并切换到它的方法吗?

小智 6

有时你必须休眠大约 5 秒,直到页面完全加载然后找到框架。

尝试这个

线程.睡眠(50000); IwebElement Frame = Driver.SwitchTo().Frame("框架的id");

//那么框架内的任何元素都应该通过这条线

Frame.FindElement(By.id("框架内元素的ID");


Mat*_*ttJ 3

主要问题是我的测试打开了一个新窗口,但我的测试是在旧窗口上查找元素。我通过使用以下命令切换到新页面来解决这个问题:

Driver.Instance.SwitchTo().Window(Driver.Instance.WindowHandles.Last());
Run Code Online (Sandbox Code Playgroud)

然后我也可以使用 SwitchTo() 切换到 iframe,如下所示:

public static bool IsAt
    {
        get
        {
            try
            {
                Driver.Instance.SwitchTo().Window(Driver.Instance.WindowHandles.Last());
                var DBViFrame = Driver.Instance.FindElement(By.Id("dashboardViewFrame"));
                Driver.Instance.SwitchTo().Frame(DBViFrame);
                var dataEntryButton = Driver.Instance.FindElement(By.Id("HyperlinkDataEntry"));
                dataEntryButton.Click();
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)