【问题标题】:Selenium Webdriver C# Drop downs in a For Loop stale element referenceSelenium Webdriver C# 在 For Loop 陈旧元素引用中的下拉菜单
【发布时间】:2019-10-11 15:12:04
【问题描述】:

当我运行 For 循环时,我只能迭代一次,而“值”不会显示为陈旧。发生了什么,我需要从第一个下拉列表中选择值来填充第二个选项。

我尝试以一种不应显示为陈旧的方式设置元素引用。

//Order Type dropdown menu
        String OrderTypeDropDown = "//*[@id='OrderTypeId']";
        IWebElement drpOrderType = driver.FindElement(By.XPath(OrderTypeDropDown));            

        //Select the order type dropdown
        SelectElement select = new SelectElement(drpOrderType);

        //Make a list of all order type dropdown options 
        IList<IWebElement> elements = select.Options;        

        //Itterate through all the options in the order type dropdown
        foreach (IWebElement value in elements)
        {
            //Click the option
            value.Click();

            //Print out the option
            Console.WriteLine(value.Text);

            //Sleep
            Thread.Sleep(3000);

            //Change Type dropdown menu stale element reference setup
            String RequestChangeDropDown = "//*[@id='RequestedChange']";

            IWebElement drpChangeType = driver.FindElement(By.XPath(RequestChangeDropDown));

            //Select the Requested Change dropdown
            SelectElement drpSelect = new SelectElement(drpChangeType);
            driver.FindElement(By.XPath(RequestChangeDropDown)).Click();

            //Make a list of all Requested Change types
            IList<IWebElement> change = drpSelect.Options;

            foreach (IWebElement option in change)
            {
                Console.WriteLine(option.Text);                   
            }

        }

错误信息: OpenQA.Selenium.StaleElementReferenceException:过时的元素引用:元素未附加到页面文档 (会话信息:chrome=77.0.3865.90) 堆栈跟踪: RemoteWebDriver.UnpackAndThrowOnError(响应错误响应) RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 参数) 远程WebElement.Click() TSR_Forms.Mobile_Device_Request_Orders() 第 907 行

【问题讨论】:

  • 最初看一下你的代码,一切都是“FindElement”,如果你想要一个列表,你将需要“FindElements”,这样所有匹配 xpath 的项目都会被迭代。

标签: c# selenium-webdriver


【解决方案1】:

您必须等到元素可点击:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
            wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.XPath(RequestChangeDropDown)));

因此,您可以单击它。 问题是你试图点击一个在 DOM 中还不能点击的元素!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 2017-12-16
    • 2012-09-05
    • 2013-04-16
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    相关资源
    最近更新 更多