0

I use selenium webdriver with C#,

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

I need to get src attribute of this element. I can locate inside of this iframe and make operations on the form which is located inside that iframe but I can't get src attribute.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
enes2101
  • 3
  • 3

2 Answers2

1

To get the iframe src attribute:

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

To interact with the iframe elements:

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

Make sure that your target iframe is not placed within some parent iframe. Otherwise, you'll have to first switch to the parent iframe to access the current one.

Max Daroshchanka
  • 2,698
  • 2
  • 10
  • 14
1

Presuming that currently you program have the visibility on the Top Level Browsing Context i.e. within the parent frame, to get the value of the src attribute of the <iframe> you have to induce WebDriverWait for the ElementIsVisible() and you can use either of the following 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"));
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352