Skip to main content
 首页 » 编程设计

C# Selenium Webdriver 在 iframe 中查找元素

2024年02月06日27luoye11

我找不到 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> 

这是我当前的代码:

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

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

请您参考如下方法:

有时您必须等待大约 5 秒,直到页面完全加载然后找到框架。

试试这个

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

//那么 frame 内的任何元素都应该通过这一行获取

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