【问题标题】:How to extract the src attribute of an iframe using Selenium and C#如何使用 Selenium 和 C# 提取 iframe 的 src 属性
【发布时间】:2022-01-12 20:43:13
【问题描述】:

我在 C# 中使用 selenium webdriver,

<iframe class="x-component x-fit-item x-component-default" id="component-1105" name="ets_grd_02_IFrame" src="frm_01_master_training_plan.aspx?RID=196&amp;RIU=U&amp;_dc=1641984641351" frameborder="0" style="margin: 0px; width: 718px; height: 535px;"></iframe>

我需要获取这个元素的 src 属性。我可以在这个 iframe 内部定位并对该 iframe 内部的表单进行操作,但我无法获取 src 属性。

【问题讨论】:

  • 到目前为止你尝试了什么并且有代码?

标签: c# selenium xpath iframe css-selectors


【解决方案1】:

获取 iframe src 属性:

driver.SwitchTo().DefaultContent(); // call this or make sure you are not already switched to this iframe
string iframeSrc = driver.FindElement(By.Xpath("//iframe[contains(@id, 'component-')]")).getAttribute("src")

与 iframe 元素交互:

IWebElement frame = driver.FindElement(By.Xpath("//iframe[contains(@id, 'component-')]"))
driver.SwitchTo().Frame(frame);
// do somethind you like within iframe
driver.SwitchTo().DefaultContent();

确保您的目标 iframe 未放置在某个父 iframe 中。 否则,您必须先切换到父 iframe 才能访问当前 iframe。

【讨论】:

    【解决方案2】:

    假设当前您的程序对Top Level Browsing Context 具有可见性,即在parent frame 内,要获取&lt;iframe&gt;src 属性的值,您必须诱导@ 987654323@ 用于ElementIsVisible(),您可以使用以下任一Locator Strategies

    • CssSelector

      Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.CssSelector("iframe.x-component[id^='component'][name^='ets_grd'][name$='IFrame']"))).GetAttribute("src"));
      
    • XPath

      Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//iframe[contains(@class, 'x-component') and starts-with(@id, 'component')][starts-with(@name, 'ets_grd') and contains(@name, 'IFrame')]"))).GetAttribute("src"));
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-08
      • 2016-06-18
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 2020-07-06
      • 2015-10-28
      相关资源
      最近更新 更多