如何使用 Selenium 和 C# 提取 iframe 的 src 属性

How to extract the src attribute of an iframe using Selenium and C#

我在 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 属性。

获取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。

假设当前您的程序在 i.e. within the , to get the value of the src attribute of the <iframe> you have to induce for the ElementIsVisible() and you can use either of the following 上具有可见性:

  • 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"));