【问题标题】:Selenium 4 error in selecting from dropdown从下拉列表中选择时出现 Selenium 4 错误
【发布时间】:2022-07-28 23:37:25
【问题描述】:

自从更新到 Selenium 4.1.2 后,我的测试在使用所有选项从下拉列表中选择值时失败:按值、索引和可见文本。请参阅下面的错误:

“JavaScriptException: 无法点击选项元素。执行 Javascript 点击函数返回意外错误,但 Internet Explorer 的 JavaScript 引擎没有返回错误。”

有什么解决方法吗?

【问题讨论】:

  • 用你的代码试验更新问题。

标签: selenium selenium4


【解决方案1】:

这似乎是在不同版本的驱动程序中反复出现的错误。但是,您可以通过定义定义 Js 代码的方法来解决下拉列表管理问题。 这个例子展示的是C#代码,但是如果你使用其他语言,原理是一样的

public void SelectOption(By by, String value) 
        {
            Actions actions = new Actions(Driver);
            IWebElement wele = Driver.FindElement(by);
            IJavaScriptExecutor jsExecutor = (IJavaScriptExecutor)Driver;
            jsExecutor.ExecuteScript("arguments[0].click();", wele);
            jsExecutor.ExecuteScript("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text.toUpperCase() == arguments[1]){ select.options[i].selected = true; } }", wele, value);
            Thread.Sleep(TimeSpan.FromSeconds(1));                 
        }

如果下拉列表中有 onclick="" 或 onchage="" 类型的函数,请记住在 js 代码中定义它们。
如下例所示,定义了 select.onchange()

 public bool SelectOptionOnChange(By by, String value)
        {
            bool failed = true;
            Actions action = new Actions(Driver);
            if (!m_sHelper.boolWaitForElementIsDisplayed(by, TimeToWait.med))
                m_sHelper.SetErrorMsg("Elemento dropdownlist non identificato: " + value);
            else
            {
                IWebElement dropElement = Driver.FindElement(by);
                SelectElement dropOptions = new SelectElement(dropElement);
                if (dropOptions.Options.Count == 0)
                    return true;
                try
                {
                    IJavaScriptExecutor jsExecutor = (IJavaScriptExecutor)Driver;
                    jsExecutor.ExecuteScript("arguments[0].click();", dropElement);
                    jsExecutor.ExecuteScript("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text.toUpperCase() == arguments[1]){ select.options[i].selected = true; select.onchange();} }", dropElement, value);
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                    failed = false;
                } catch (Exception)
                {
                    failed = true;
                }
            }
            return failed;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多