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



我将selenium网络驱动程序与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>

我需要得到这个元素的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。

假设当前您的程序在顶层浏览上下文上具有可见性,即在父框架内,要获得<iframe>src属性值,您必须诱导WebDriverWait等待ElementIsVisible(),并且您可以使用以下定位器策略之一:

  • CsSelector:

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

最新更新