【问题标题】:How to select Iframe in Selenium?如何在 Selenium 中选择 iframe?
【发布时间】:2016-04-21 07:06:35
【问题描述】:

我想选择 id="iframe00237" 的 iframe 和其中的数据:

这是 HTML:

<iframe src="http://example/iframe/v2.html?id=5225dddd-588a-49c2-961e-e3417cf5a728  scrolling="no" frameborder="0" marginwidth="0" marginheight="0" width="100%" height="100%" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" id="iframe09328" class="sm_iframe"></iframe>
    <body>
        <div>
            <iframe src="http://example.com/main?id=aab0619b-a938-4f00-b545-742fff5e1118&amp;crtdt=1461214262&amp; scrolling="no" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen="allowfullscreen" id="iframe05443" class="sm_iframe" style="left: 0px; top: 0px; width: 730px; height: 411px;"></iframe>
        </div>
        <div>
            <iframe src="http://example.com/main?id=5225dddd-588a-49c2-961e-e3417cf5a728&amp scrolling="no" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen="allowfullscreen" id="iframe00237" class="sm_iframe" style="left: 0px; top: 0px; width: 811px; height: 456px;"></iframe>
        </div>
    </body>

Iframe src="url" url 是随机的..

我在 Stackoverflow 中找到并尝试使用代码:

//Select parent frame
IWebElement parentFrame = driver.FindElement(By.XPath("//iframe[@id='iframe09328']"));
driver.SwitchTo().Frame(detailFrame);

//Current we on detailFrame continues to go to childFrame.
IWebElement childFrame = driver.FindElement(By.XPath("//iframe[@id='iframe00237']"));
driver.SwitchTo().Frame(childFrame);

在调试模式下,parentFramechildFrame 始终为 null 值。

如何解决我的问题?我也试试FindElement by ID

【问题讨论】:

标签: c# selenium iframe


【解决方案1】:

如果 ID 是静态的,您可以使用 By.Id()。见以下代码:

IWait<IWebDriver> wait = new DefaultWait<IWebDriver>(driver);
wait.Timeout = TimeSpan.FromSeconds(10);
wait.PollingInterval = TimeSpan.FromMilliseconds(300);
By by = By.Id("iframe09328");
try
{
    // Switch to the parent iframe
    wait.Until(d => d.FindElements(by).Count > 0);        
    IWebElement parentFrame = driver.FindElements(by).First();
    driver.SwitchTo().Frame(parentFrame);

    // Switch to the inner iframe
    by = By.Id("iframe00237");
    wait.Until(d => d.FindElements(by).Count > 0);
    IWebElement childFrame = driver.FindElements(by).First();
    driver.SwitchTo().Frame(childFrame);
}
catch (Exception)
{
    throw new NoSuchElementException("Unable to find element, locator: \"" + by.ToString() + "\".");
}

如果这不起作用,请给我们异常“无法找到元素,定位器:......”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    相关资源
    最近更新 更多