Selecting an item from a drop-down menu using WebDriver in Java - the ultimate guide!

Having a dropdown button, clicking it will open a list of items to choose from. Here's the HTML:

<button id="btn-append-to-body" class="btn btn-primary mobile-quick-button dropdown-toggle" type="button" uib-dropdown-toggle="" aria-haspopup="true" aria-expanded="false">
<div class="clearfix">
<span class="pull-left text-left ng-binding" tabindex="0">   Select one </span>
<span class="pull-right text-right ng-binding">
</div>
</button>
<ul class="uib-dropdown-menu dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
<li id="quickOption" class="ng-scope" role="presentation" name="quickOption" ng-repeat="option in dropOptions" ng-click="selectOption(option)" required="" tabindex="0" style="">
<a href="">
<div class="clearfix">
<span class="pull-left ng-binding">frame number</span>
</div>
</a>
</li>
<li id="quickOption" class="ng-scope" role="presentation" name="quickOption" ng-repeat="option in dropOptions" ng-click="selectOption(option)" required="" tabindex="0">
<a href="">
<div class="clearfix">
<span class="pull-left ng-binding">serial number</span>
</div>
</a>
</li>
</ul>

To select an item from this list, you can use the following code:

public void lookupSearch (String item){
driver.findElement(By.xpath("//*[@id='btn-append-to-body']")).click();
//then i choose/click the parameter item (i.e frame number or serial number)
}

Passing the desired item as a parameter.

Please provide guidance on how to properly select the item.

Answer №1

If you need to select an item from a drop-down menu by clicking on a button and choosing from a list, you can use the code snippet below:

public void chooseItemFromDropDown(String item) {
    driver.findElement(By.xpath("//button[@id='btn-append-to-body']/div/span[contains(.,'Select one')]")).click();
    WebDriverWait wait4elements = new WebDriverWait(driver, 10);
    List<WebElement> myElements = wait4elements.until(ExpectedConditions.numberOfElementsToBe(By.xpath("//ul[@class='uib-dropdown-menu dropdown-menu']/li/a/div/span"), 2));
    
    for (WebElement element : myElements) {
        if (element.getAttribute("innerHTML").contains(item)) {
            element.click();
            break;
        }
    }
    
    System.out.println("Element with text: " + item + " has been selected");
}

Answer №2

Here is the response showcasing how to find the number of Li elements within a ul list, retrieve the text from each li element, and compare it with the provided item string.

WebElement uList = driver.findElement(By.xpath("//*[@id='quick-search-dropdown']/ul"));
            List<WebElement> listCount = uList.findElements(By.tagName("li"));
            for (int i = 1; i <= listCount.size(); i++) {
                WebElement lookupItem = driver.findElement(By.xpath("(//li[@id='quickOption']/a/div/span[1])[" + i + "]"));
                String lookupItemValue = lookupItem.getText();
                if (lookupItemValue.equalsIgnoreCase(Item)) {
                    lookupItem.click();
                }
            }

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

Tips for bypassing captcha and avoiding Selenium detection

I wrote a Python script that logs into a specific page (sso.acesso.gov.br) using certain credentials and then typically solves a captcha using the 2Captcha API. However, recently I have been encountering an error after solving the captcha, even when I do ...

Easy steps to resolve the problem encountered with Chrome Driver and Chrome browser

When attempting to run a basic script in Selenium Web Driver, I encountered an issue. The Chrome driver version is 80.0 and the Chrome browser version is 80.0. After running the program, all I see is a blank window. I also came across the following sugges ...

Fields are unable to process the input provided

While testing my website's cart functionality, I encountered an issue with inputting data into the Debit card fields after selecting the Payment method. How can I successfully enter data into these fields? You can access the Website to be tested via t ...

Tips for capturing network traffic with Selenium WebDriver and BrowserMob Proxy in Python

For my project, I am working on capturing network traffic using Selenium Webdriver with Python. In order to achieve this, I need to utilize a proxy such as BrowserMobProxy. Everything works smoothly when using webdriver.Chrome: from browsermobproxy impor ...

Discover the most up-to-date version of the Chrome driver for seamless integration with Selenium

I am looking for the most up-to-date Chrome driver to run my Selenium project. I attempted to follow the link provided by Visual Studio Code, but the highest version I could find is 114. The latest version available for download is actually 122.0.6261.95 ...

Mastering Mockito for mocking org.openqa.selenium.support.ui.Select components

Unit testing is a vital part of my Selenium integration tests, and in order to effectively test them, I need the ability to mock the selenium Select Object. The method I am testing: protected int findOptionByIgnoreCaseText(String value, Select dropDown) ...

Error occurred in the main thread: org.openqa.selenium.InvalidElementStateException:

Today, I encountered an issue while trying to send input string to the search text box on a Chrome browser: // attempting to search for a text in Google WebDriverWait wait3 = new WebDriverWait(driver1,30); WebElement textBox = wait3.until(ExpectedConditio ...

An error has been encountered in the main thread: java.lang.IllegalStateException - The driver executable required for Selenium in Java is missing

Oh no! An error has occurred: Exception in thread "main" java.lang.IllegalStateException: The driver executable must exist Here are the code trials that led to this issue: import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.C ...

I am having difficulty locating or clicking on an element on my page using Selenium, Python, findelement, and Xpath methods

I am facing difficulty in locating an element on a webpage after logging in successfully to the website. My goal is to click on a button that appears only after midnight to participate in an activity. However, I do not want to stay glued to my PC just to ...

Tips for efficiently scraping multiple hrefs within a webtable using Selenium

I am currently faced with the challenge of web scraping a website using Python and Selenium. The information I need is spread across different pages linked in the 'Application number' column. How can I programmatically click on each link, navigat ...

Trouble with clicking the button in Selenium Webdriver? Element located but unable to be clicked

Can anyone assist me in finding a solution to my current problem? I have dedicated a significant portion of today trying various solutions both on this platform and through Google. To get straight to the point, I am facing an issue with Selenium automatio ...

Facing a Chromedriver malfunction on my Django application hosted on the DigitalOcean App Platform

I am currently working on a web application using Django and the App platform on DigitalOcean. I have integrated Selenium and Chromedriver into my app, and I was able to install Chromedriver using Python libraries such as chromedriver_binary via pip. Howev ...

The steps for changing instances in WebDriver

Hello, I currently have a setup with my framework that involves the following: ClassA { // This class receives Selenium WebDriver calls through the 'driver' object reference to interact with UI elements public WebDriver get() { ...

Splinter: Extracting XPATH text fragments that do not comprise distinct elements

How can I extract and store the text of the first, underlined, and last parts of the question using Splinter? Refer to the HTML below. I aim to assign the following values to variables: first_part = "Jingle bells, jingle bells, jingle all the" second_par ...

Trouble arises with the Selenium feature when attempting to choose a particular article within a Tree component by utilizing a dynamic XPath

Currently, I am working on developing a Selenium function that has the ability to select a specific article within a Tree component. This particular article has been previously identified using the search bar and is the only available element at that time. ...

Error: The object of type 'WebElement' cannot be accessed with square brackets

I am attempting to use Python to click the Replay button on Spotify's Web Player, but I keep encountering an error. How can I go about clicking buttons in a web player? replay = driver.find_element_by_xpath("""/html/body/div[2]/div/div[ ...

Unable to access code search functionality during the process of scraping from GitHub

Trying to create a simulation of the online GitHub search using Selenium web scraping. Struggling to make the program search within the Code section instead of repositories. Here is the code snippet: FirefoxProfile p = new FirefoxProfile(); p.setPref ...

Selenium WebDriver textWait()

When testing AJAX applications, is there a specific waitForText() method in Selenium WebDriver that can be used? Essentially, I'm looking to verify the appearance of new or updated elements/text after an AJAX request. Is there a sample code snippet ...

Currently, I am utilizing Selenium-webdriver and require the capability to choose an element based on its textual content

Having an issue with finding an element using the current xpath and need a dynamic solution. public void selectCheckBox(WebElement wrapper, String value) { scrollTo(wrapper); String xpath = ".//label[span/text()='" + value + "& ...

Having trouble with clicking the button on the user login page of the rediff.com website

Having trouble clicking on a button after entering the email address. driver = new ChromeDriver(); driver.get("http://in.rediff.com/"); driver.findElement(By.xpath(".//*[@id='homewrapper']/div[5]/a[3]/div/u")).click(); dr ...