The functionality of SelectByText (partial) in C# Selenium WebDriver bindings appears to be malfunctioning

I am currently facing an issue using the Selenium WebDriver Extensions in C# to select a value from a select list by matching partial text. Despite trying different approaches, I can't seem to get it to work as expected. Could this be a mistake on my end or possibly a bug?

Below is a reproducible example:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;

namespace AutomatedTests
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("http://code.google.com/p/selenium/downloads/list");
            var selectList = new SelectElement(driver.FindElement(By.Id("can")));
            selectList.SelectByText("Featured downloads");
            Assert.AreEqual(" Featured downloads", selectList.SelectedOption.Text);
            selectList.SelectByValue("4");
            Assert.AreEqual("Deprecated downloads", selectList.SelectedOption.Text);
            driver.Quit();
        }
    }
}

The error message received is:

OpenQA.Selenium.NoSuchElementException: Cannot locate element with text: Featured downloads

Answer №1

When I encountered issues with the SelectByText method, I took matters into my own hands and created a custom extension method called SelectBySubText to perform the necessary functionality.

using System.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

namespace CustomExtensions
{
    public static class WebElementCustomExtensions
    {
        public static void SelectBySubText(this SelectElement element, string subtext)
        {
            foreach (var option in element.Options.Where(option => option.Text.Contains(subtext)))
            {
                option.Click();
                return;
            }
            element.SelectByText(subtext);
        }
    }

Answer №2

If you are able to recreate the issue on a basic HTML page, it is recommended that you report it as a bug.

Upon reviewing the source code, the method SelectByText first executes this:

FindElements(By.XPath(".//option[normalize-space(.) = " + EscapeQuotes(text) + "]"))

If no elements are found, it then tries:

string substringWithoutSpace = GetLongestSubstringWithoutSpace(text);
FindElements(By.XPath(".//option[contains(., " + EscapeQuotes(substringWithoutSpace) + ")]"))

In theory, this approach should work. You can also experiment with the XPath expression yourself to see if you can make it function in your particular scenario.

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

The building process encountered an error while trying to import cucumber

Currently, I am in the process of constructing a framework. However, I have encountered a build failure error related to the cucumber import. If anyone can offer assistance on this matter, it would be greatly appreciated. ...

Request for Selenium element

I'm struggling to locate an element using the Selenium library. I've attempted to find it by id, by Xpath, but so far, no luck... I suspect the issue lies within the HTML iframe or framesets, despite also trying driver.switch_to.frame without any ...

Office network causing browser stack unreachable browser error

Seeking assistance with resolving an exception error when attempting to connect to BrowserStack using Selenium code. 1. Every time we run the line of code `WebDriver driver = new RemoteWebDriver(new URL(URL), caps);`, we encounter an unreachable browser e ...

Selenium encountered an exception: WebDriverException - Error message: Chrome encountered an unknown issue while attempting to launch, resulting in an abnormal exit with ChromeDriver, Selenium

While attempting to execute a webscraper on a linux server, I encountered the following error: selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.10.267518,platfor ...

What is the best method for locating X-Path for elements inside a frameset?

I need help creating a test case for Selenium because I am struggling to locate elements on my website. The issue seems to be related to the fact that my site uses an HTML frame set. When I try to select all links using Firebug: //a I do not get any res ...

Cannot bring in the module 'selenium'

I'm facing a seemingly simple issue that has me stumped. Despite installing selenium and chromedriver with the correct version for my browser, I keep receiving an error message in VSCode that reads "Unable to import 'selenium'." Here's ...

Testing a cucumber scenario by comparing the redirect URL with a different URL

Currently, I am working on writing Cucumber tests for my project. One issue I have encountered is that when clicking a certain button in my code, it redirects to another page with a fixed URL. How can I retrieve the current URL within the Cucumber test? I ...

ASP repeater exceeding container boundaries

Having trouble with my asp repeater that reads from a database and generates repeatable divs. The issue arises when the h4 spills over the div, particularly when using <%Eval. Any suggestions on how to fix this? Manual input divs don’t seem affected o ...

Duplicate browser session using Selenium WebDriver

Is it possible to continue using the same Firefox browser session with Selenium WebDriver if the current browser crashes or is closed? For example, if I have 1000 lines of code to check and the browser crashes while debugging at line 800, causing my IDE ( ...

Tips on automating mouse clicks in Selenium (Java) for elements located within a div with a higher z-index

How can I make Selenium interact with buttons within a modal that has a higher z-index? CSS: .buX { background-color: #fff; display: flex; flex-direction: column; outline: none; padding: 0; position: absolute; width: 504px; ...

When using Selenium, interacting with the "Accept cookies" banner is as simple as a click

Starting my journey with selenium and came across an issue with a cookie banner: I am attempting to navigate to the website "https://couchnow.com/" using Selenium and click on the "Alles akzeptieren" Button (which accepts all the cookies). I tried locati ...

Automate image clicking on web pages using Selenium and JavaScript with Python

I'm currently using Selenium to attempt clicking on a JavaScript image within a website, but I'm struggling to accomplish this task. Here is the code I have thus far: from selenium import webdriver from selenium.webdriver.common.keys import Key ...

The unsuccessful functionality of Junit tagging in Selenium webdriver

I am currently utilizing Selenium Webdriver along with cucumber, gherkin, and java. I have tagged all my scenarios with labels such as @website, @wip, @disabled, etc. Whenever I attempt to use a junit runner to create specific test sets, it ends up execut ...

Tips for extracting the URL of a fresh webpage using Selenium and Scrapy

I'm currently working on a web-scraping project to extract data from a platform known as "Startup India," which facilitates connections with various startups. I have set up filters to select specific criteria and then click on each startup to access d ...

IIS5 upgraded to enhance AJAX functionalities

Currently, I am working on a project in VS2010 using ASP.NET MVC 2. The development has been completed, but when trying to deploy the project on IIS, issues start to arise. The AJAX request that triggers a controller method is not functioning properly on ...

Strategies for Dealing with a selenium NoSuchElementException

I'm struggling to grasp the correct approach for handling selenium when it encounters difficulty finding an element. The code I am currently using looks like this: WebDriver driver = new PhantomJSDriver(); for (FeedItem item : items){ String ur ...

Is there a variation in HTML/XHTML/XML code based on different geographic regions?

I have a question regarding the consistency of HTML, XHTML, and XML code across different localizations. If I write code on a system using the "en-us" localization, will it remain the same when rendered on a system with the "sv-SE" localization? For examp ...

The data contract for type 'Newtonsoft.Json.Linq.JToken' is a recursive collection that is not supported. Please consider adjusting the collection definition

I am encountering an issue while trying to iterate through the server's response. The error message I keep receiving is: The data contract 'Type 'Newtonsoft.Json.Linq.JToken'' is a recursive collection, which is not supported. To ...

c# selenium code to interact with submit button element

Is there a way to extract text from an input box? <input value="Add a Phone" onclick="CSS.addClass($(&quot;u_0_4&quot;), &quot;async_saving&quot;); new AsyncRequest().setURI(&quot;\/ajax\/phone\/confirma ...

Having trouble with file upload using SendKeys in Selenium?

When attempting to upload a file using chromedriver, I first locate the Browse button element and use Click() to initiate the file upload process. However, upon opening a new window to enter the file path, the SendKeys method fails to type in the filepath. ...