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

问题描述 投票:1回答:3

因此,当我点击按钮时,我会弹出一个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>
c# selenium iframe xpath selenium-webdriver
3个回答
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);

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

也可以使用css选择器:

iframe[id*='dctPopup']

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

//iframe[contains(@id, 'dctPopup')]
© www.soinside.com 2019 - 2024. All rights reserved.