C#:使用木偶驱动程序选择下拉项

本文关键字:选择 驱动程序 | 更新日期: 2023-09-27 17:55:42

我正在使用带有C#绑定的Selenium Webdriver,并尝试从旧的FirefoxDriver(FF 47之前)切换到新的Marionette driver(FF47及更高版本),并且在一些初期问题之后工作得很好,这些问题似乎随着Selenium 2.53.1FF 47.0.1的发布而得到解决。

现在唯一的问题是,在选择标签下选择选项标签似乎有问题。以下代码适用于我正在测试的所有其他浏览器(FF <46,Chrome,IE)。我将以下参数传递到我的dropdownSelect函数中。选择IWebElement和要搜索的文本。下面是函数定义:

public static void dropdownSelect(IWebDriver driver, IWebElement inObject, string inText)

我尝试像使用所有其他浏览器一样使用 SelectElement()

select = new SelectElement(inObject);
//select the matching element
select.SelectByText(inText);

我还尝试获取该选项的集合并使用两个Click()滚动浏览集合:

IJavaScriptExecutor js = driver as IJavaScriptExecutor;
ReadOnlyCollection<IWebElement> optDropdown;
optDropdown = inObject.FindElements(By.TagName("option"));
foreach (IWebElement thsItem in optDropdown)
 {
   //check for matching text
    if (thsItem.Text == inText)
     {
       // 1/4 second wait
       Thread.Sleep(250);
       thsItem.Click()
       //exit foreach loop
       break;
     }
 }

以及javascript单击以代替thsItem.Click()段代码

//click option element
js.ExecuteScript("arguments[0].click();", thsItem);

不会选择任何内容,也不会引发任何错误或异常。它只是继续它的快乐方式,没有选择任何东西

我做错了什么,还是新的木偶司机仍在解决?

C#:使用木偶驱动程序选择下拉项

尝试使用ExecuteScript()进行整个操作,如下所示:-

public static void dropdownSelect(IWebDriver driver, IWebElement inObject, string inText) {
   IJavaScriptExecutor js = driver as IJavaScriptExecutor;
   js.ExecuteScript("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", inObject, inText);
}

希望它会起作用:)

我通过使用类似于上面描述的 JavaScript 来解决这个问题。由于当它发生变化时存在对此下拉列表的依赖性,我只是在 Selenium 中找到它时选择了适当的选项,即使使用 Javascript 也触发了 onchange

这是选择框的 HTML

<select class="T2FormControl"   id="ctl00_pageContent_TableList_T2DropDownList_DropDownList" onchange="javascript:setTimeout('__doPostBack(''ctl00$pageContent$TableList$T2DropDownList$DropDownList'','''')', 0)" name="ctl00$pageContent$TableList$T2DropDownList$DropDownList">

以及执行该操作的 Javascript

//click option element and for change event
js.ExecuteScript("arguments[0].selected = true;" +
                 "var element=arguments[1];" +
                 "var event=document.createEvent('"HTMLEvents'");" + 
                 "event.initEvent('change', false, true);" +
                 "element.dispatchEvent(event);", thsItem, inObject);

其中 IWebElement thsItem 是所选选项,IWebElement inObject 是下拉列表的选择标记

似乎是执行其他Selenium驱动程序自动执行的操作的迂回方式,但它有效