C#: How to Automatically Choose Dropdown Options Using Marionette Driver

Currently, I am utilizing Selenium Webdriver alongside C# bindings and transitioning from the outdated FirefoxDriver (pre-FF 47) to the newer Marionette driver (FF47 and above). The switch has been successful after encountering some initial challenges that were resolved with the update of Selenium 2.53.1 and FF 47.0.1.

However, an issue arises when attempting to select option tags within a select tag. The code functions properly for all other browsers tested (FF < 46, Chrome, IE). Parameters passed into the dropdownSelect function include the select IWebElement and the desired search text. Here is the definition of the function:

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

I have experimented with using the SelectElement() class similar to other browsers:

select = new SelectElement(inObject);

//select the matching element
select.SelectByText(inText);

Additionally, I attempted to retrieve a Collection of the options and iterate through them using 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)
     {
       Thread.Sleep(250); // 1/4 second wait

       thsItem.Click();

       //exit foreach loop
       break;
     }
 }

I also tried invoking a javascript click instead of thsItem.Click():

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

Although no errors or exceptions are thrown, nothing gets selected. It progresses without any selection made. Is there an error on my end, or is this still a work in progress with the Marionette driver?

Answer №1

Experience the entire operation using ExecuteScript() like this:

public static void selectDropdownItem(IWebDriver driver, IWebElement dropdownElement, string itemText) {
   
   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; } }", dropdownElement, itemText);
    
}

Fingers crossed that it works...:)

Answer №2

I discovered a solution using Javascript, similar to the method mentioned earlier. I found that by identifying the dropdown dependency and selecting the appropriate option in Selenium, then triggering the onchange event with Javascript, the issue was resolved.

Below is the HTML code for the select box:

<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">

And here is the Javascript function that executes the action:

//click on the option element and trigger 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);

Here, thsItem represents the selected option as an IWebElement, and inObject represents the select tag for the dropdown.

While this approach may seem indirect compared to other Selenium drivers that handle this automatically, it proved effective in resolving the issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Miscalculation of Volume when Subdivisions are set to 0

After reaching out for help on Volume Calculation, I found valuable assistance in this specific thread. Since then, I've developed a function that accurately calculates the volume of a closed mesh using Three JS. In my implementation, the variable fac ...

The absence of a semicolon in the non-null assertion is causing an

Within my code, I have a function that arranges a set of cards according to a specific coordinate system: const orderCardsInPage = (items: OrderItemType[], pageCards: CardType[]) => { return pageCards.sort((firstCard, secondCard) => { con ...

Configuring webpack for live reloading and Hot Module Replacement on static pages

The title of this post may not be very clear, but I appreciate your patience. I am currently in the process of setting up React for an older Rails application that uses static ERBs. Due to the size of the project, I am gradually transitioning towards a Si ...

Remove a file from a directory using AJAX in an ASP.NET C# application

I've been attempting to remove a file from a folder using AJAX and Handler.ashx. I have a link that, when clicked, calls the removeFile() method which then invokes a method in handler.ashx to delete the file. However, the process is not functioning as ...

It is not possible for ReactJS to disable a button that has been created dynamically

Incorporating ReactJS, I dynamically generate a form using customized JSON data. render() { return ( <div> <ShowForm src={this.state.data} /> </div> ); } After updating with componentDidUp ...

Struggling to create consistent spacing between stacked bar charts in React using Recharts?

I have successfully created a stacked bar chart, but I am struggling to add a 10px spacing between two vertical stacked bar charts. I tried using barGap={8880} and barCategoryGap={100}, but it did not work as expected. Below is the code snippet and stackbl ...

The initial item in a pagination/list is double-parsed on an AJAX website using Selenium 3.0.2, Firefox webdriver, and BeautifulSoup 4.5.1

For the past three days, I've been facing a frustrating issue with both Selenium and Bs4. While I suspect Selenium (or my code) to be the culprit. Like many others before me, I'm attempting to scrape data from this website: I'm moving from ...

Challenges arising from updating the size and position of a div element during a mouse move event

As I work on creating a basic horizontal split pane using HTML, CSS, and JavaScript, I have drawn inspiration from this post. While the vertical split pane functions smoothly, the horizontal version seems to be glitchy. The sizes and positions of the div ...

Utilizing a potentially existing Angular service

Currently, I am engaged in a project using Angular that focuses on being highly modular. This means that different sections of the application can be enabled or disabled for various clients using Webpack. While this structure has been effective for me, I h ...

Immersive full-page backdrop image

My HTML page has a background image set through CSS: html{ margin-top:10px; background: url(xxxxx.jpg) no-repeat center center fixed; background-size: cover; } I am trying to change the background image dynamically from the Javascript side. ...

Navigating views with ReactJS using ES5

I have been searching for ReactJs guides, but most of them are based in ES5. As a result, I have begun using ReactJS in this manner. Now that I understand how to create all my components, I am ready to build a small single-page-application. However, I am s ...

The error message "TypeError: Cannot access the tapAsync property because it is undefined"

"webpack": "^7.89.0", "webpack-cli": "^6.2.8", After updating webpack to the versions above, I encountered this error: clean-webpack-plugin: /home/itrus/react/living_goods/build has been removed. TypeError: Cannot r ...

Assassin eradicated from list of cast members

In my quest to select a killer from the Cast Members Array for the game, I want the function to pick one person as the killer and then remove them from the castMember player array. Once the killer is chosen, they should be removed from the survivors array ...

Kineticjs is not performing up to par

I apologize if this question has already been asked, but I haven't been able to locate it. I am working on a project that involves a canvas displaying approximately 400-500 rectangles, each ranging in height and width from 20-30 pixels. The goal is t ...

Establish a default route within a Node Express application to handle multiple generic URLs (url/index, url/index2, url/index3, and

Currently, I am in the process of learning React and Express frameworks through exercises provided by NodeSchool.io. My goal is to consolidate all exercise files into a single application with multiple pages named as: index index2 index3 index4 .. ...

Angular 2 TypeScript: The concat() function operates as mutable within the framework

When I declare an array on an @Injectable provider, my intention is to use it across different components. normeList: any[] = [ { name: 'choice 1', type:'false' }, { name: 'choice 2', typ ...

Comparing the start and end times in tabular or array input using Yii2

Can I compare the start and end times in the Yii2 client/ajax validation for my form? https://i.sstatic.net/bC48T.png This is how my view file code looks: <?php foreach ($model->weekDaysList as $index => $value) : ?> <div class="row"& ...

Tips for entering text into an input field

driver.get("https://beta.stress.pw/login") enter_searchbar.element = driver.find_element_by_xpath("/html/body/div[1]/div/div[2]/form/div/div[2]/input[1]") enter_searchbar.send_keys("itartinas1") An error occurred with the fol ...

The Battle of Shared Data: Global Variables vs. ASP.NET Session State

I am currently building a web application that consists of multiple pages, all of which create an instance of the same class object with methods for interacting with a CMS API. When users begin creating content, I store variables like folder ID in a Sessio ...

Develop a React npm package with essential dependencies included

I have been working on developing a UI library using React ts. As part of this project, I integrated an external library called draft-js into the package. However, when I attempt to implement my library in another project, I keep encountering errors. Despi ...