SwitchTo IFrame,其中XPath包含id的一部分

时间:2017-12-15 12:09:06

标签: c# selenium iframe xpath selenium-webdriver

因此,当我点击按钮时,我会弹出一个iframe,我正在尝试切换到此iframe。我面临的挑战是iframe的ID是动态的,具体取决于会话,所以我需要根据id的前缀切换到iframe,无论如何都是相同的。

    public void StartMTATransaction(string date)
    {
        Transaction.Clear();
        Transaction.SendKeys("MTA");
        Go.Click();
        ObjectRepository.Driver.SwitchTo().Frame(ObjectRepository.driver.FindElement(By.XPath("//iframe[starts-with(@id,'dctPopup_dctPopupWindow') and contains(@name,'dctPopup_dctPopupWindow')]")));
        TransactionDate.SendKeys(date);
        ObjectRepository.driver.SwitchTo().DefaultContent();
    }

当我尝试运行代码时,在第2行获得以下错误:

  

System.NullReferenceException:'对象引用未设置为对象的实例。'

元素我想切换到:

<iframe id="dctPopup_dctPopupWindow5D21CAC8BEAC0794DFC40B9D0081D49E" style="WIDTH: 100%; HEIGHT: 100%; BACKGROUND-COLOR: transparent" name="dctPopup_dctPopupWindow5D21CAC8BEAC0794DFC40B9D0081D49E" frameborder="0" width="100%" height="100%"></iframe>

3 个答案:

答案 0 :(得分:1)

尝试以下操作,您的xpath需要更正。

Go.Click();   
ObjectRepository.Driver.SwitchTo().Frame(ObjectRepository.driver.FindElement(By.XPath("//iframe[contains(@id, 'dctPopup_')]")));
TransactionDate.SendKeys(date);

正确的xpath是//iframe[contains(@id, 'dctPopup_')]

答案 1 :(得分:1)

使用css选择器也是可能的:

iframe[id*='dctPopup']

如果您想坚持使用xpath,请尝试:

//iframe[contains(@id, 'dctPopup')]

答案 2 :(得分:1)

根据HTML切换到 IFrame ,您可以使用以下代码块:

Go.Click();   
ObjectRepository.Driver.SwitchTo().Frame(ObjectRepository.driver.FindElement(By.XPath("//iframe[starts-with(@id,'dctPopup_dctPopupWindow')]")));
TransactionDate.SendKeys(date);

通过耦合name属性,您可以更精细:

Go.Click();   
ObjectRepository.Driver.SwitchTo().Frame(ObjectRepository.driver.FindElement(By.XPath("//iframe[starts-with(@id,'dctPopup_dctPopupWindow') and contains(@name,'dctPopup_dctPopupWindow')]")));
TransactionDate.SendKeys(date);

但是根据最佳做法,我们应该为WebDriverWait引导 IFrame 以便切换,如下所示:

Go.Click();
_wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(6));
_wait.Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(By.XPath("//iframe[starts-with(@id,'dctPopup_dctPopupWindow') and contains(@name,'dctPopup_dctPopupWindow')]")));
TransactionDate.SendKeys(date);