How to choose an item from a dropdown menu using cssSelector in Java webdriver

When I click a button to open a drop-down menu, I am attempting to select specific elements in webdriver. The button clicks fine and the dropdown pops down successfully.

WebElement providers = driver.findElement(By.id("providers"));
      providers.click();

The HTML code is as follows:

<input id="providers" class="providersOff" type="button">
<div id="providers-list" class="">
    <ul>
        <li ng-click="searchProvider(0)">
            <div class="imageContainer">
                <span>Google</span> <--TRYING TO SELECT THIS

I am specifically trying to select the Google element within the list.

I have attempted the following selectors without success:

driver.findElement(By.cssSelector(".imageContainer[Google]"));
driver.findElement(By.cssSelector(".providers-list > li[ng-click*= searchProvider(0)]"));

However, the following commands run perfectly:

  // Assign search-bar & send keys
      WebElement searchbar = driver.findElement(By.id("txtSearch"));
      searchbar.sendKeys("Pizza");


      // Assign provider drop-down & click
      WebElement providers = driver.findElement(By.id("providers"));
      providers.click();

Answer №1

To achieve this:

div.imageContainer > span

essentially denotes:

Select the span element that is directly nested inside a div element with the class of imageContainer.

To extract the actual text, utilize .text:

WebElement span = driver.findElement(By.cssSelector("div.imageContainer > span"));
System.out.println(span.text);

If you wish to target the span based on its content, you can leverage xpath:

WebElement google = driver.findElement(By.xpath("//div[@class='imageContainer']/span[. = 'Google']"));
google.click();

Alternatively, you can depend on the ng-click attribute within the li element:

WebElement span = driver.findElement(By.cssSelector("li[ng-click$='(0)'] > div.imageContainer > span"));

where $= signifies an ends-with selector.

Answer №2

Have you ever tried playing a game to learn basic CSS selectors? I found it really helpful:

Regarding your question, based on the code snippet you shared, the shortest possible selector is just span.

driver.findElement(By.cssSelector("span"));
- this selects any html tag 'span', which may not be unique if you have multiple spans on your page.

driver.findElement(By.cssSelector("#providers-list span"));
- searches for a span element within an element with id=providers-list. This should work, but if there are many spans within that specific div, you can try:

driver.findElement(By.cssSelector("#providers-list .imageContainer span"));
- looks for a span inside an element with id=providers-list, where the descendant has a class attribute containing imageContainer.

You could also specify the full path to the element:

driver.findElement(By.cssSelector("#providers-list > ul > li > .imageContainer > span"));
- '>' indicates a direct child, while space means a descendant (regardless of depth).

EDIT

If ng-click is the only unique attribute, your code will look like:

driver.findElement(By.cssSelector("#providers-list li[ng-click='searchProvider(0)'] > .imageProvider > span"));

EDIT2

After expanding the dropdown (by clicking providers), make sure to wait for the element to become visible.

WebDriverWait wait = new WebDriverWait(driver, 10);
String selector = "#providers-list li[ng-click='searchProvider(0)'] > .imageProvider > span";
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(selector)));

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 error message "cannot subscript the object of type 'type'" occurs when using Python Selenium

Hello! I am just starting to explore the world of Python Selenium. Here's a code snippet I put together. from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait import unittest class LoginTest(unittest.TestCase): ...

Selenium in combination with Python anticipates a particular element that has already been located

I'm having trouble using the expect method on an object that is already located. The issue arises when I try to interact with the element after it has been clicked, as it mutates into one of many similar input elements and can only be distinguished by ...

Once I sign in, the activity fails to switch

As someone who is new to Android Studio, I recently attempted to create a small application with a Google sign-in button on the initial activity. However, upon clicking the Google Sign In button and selecting an account, the app remained on the same activi ...

Encountering issues with installing GWT on Eclipse Juno

After numerous attempts to install GWT, I continue to encounter the same error message. Despite following advice from various sources such as running Eclipse as an administrator and updating Eclipse itself, the problem persists. My current setup includes ...

Is it not possible to check the server control checkbox in ASP.NET?

When attempting to implement a toggle button in my project, I encountered an issue where a server control checkbox cannot be checked. However, when using an HTML control, the checkbox can be checked. What could I be overlooking? <div class="material- ...

Using ReactJS to create cross-browser inline styling with flexbox

I'm currently working on a React web application that relies heavily on inline styling. My goal is to ensure compatibility with the latest versions of major browsers (Safari, Chrome, Firefox, IE) while utilizing flexbox for layout. The issue I encou ...

The input and label are not experiencing any overflow

I've been following a tutorial to create an animation on an input and label. I successfully did it once today in school, but for some reason, it's not working now. My objective is to have the label inside the "input" field, with the input taking ...

consistent character spacing for a custom font upload

Developing an application that necessitates counting up and opting for the font Orbitron due to its square appearance. The issue arises as, unlike the default chrome font, the width of this font's digits is not consistent, causing the count character ...

Adding a border to the input field in Bootstrap for enhanced styling and visibility

Looking to replicate the border style on an input element as shown in this image: https://i.sstatic.net/a2iwZ.png The current code I have is producing a different result. Can anyone assist me in achieving the desired border style? <!DOCTYPE html> ...

Finish the activity or invoke finish() from a ContextWrapper subclass

In my coding setup, I have an activity with viewPager. Picture Post_Home as the activity that extends AppCompatActivity. Additionally, there's another class called Post__Home which extends ContextWrapper. Description of Post__Home Class: public clas ...

Mapping RestTemplate to an object

My current challenge involves using RestTemplate to make a webservice call. Right now, I am using the Object type instead of a specific user-defined one, which is my ultimate goal. Here is the response I am getting from the web service: {Locales=[{Code=a ...

Utilizing Selenium and BeautifulSoup to extract data from a website

I am currently in the process of scraping a website that dynamically loads content using JavaScript. My objective is to create a Python script that can visit a site, search for a specific word, and then send me an email if that word is present. Although I ...

Menu items on the responsive design are vanishing

I am facing an issue with my sample menu layout. It appears fine on desktop view, but when I switch to a smaller window size of 480px, the items from About to Contact disappear when I hover away from the last item in the .has-children class. It seems like ...

Dynamic auto-complete feature in C# WinForms enables users to effortlessly find and select

As a newcomer to C# programming, I have set out to create a small app that will assist in searching through all of our tests. The app includes a search box and a button that, when clicked, uses the button_click method to perform a 'contains' quer ...

Utilize CSS to format the output of a script embedded within

When I embed the following script in my HTML, the output doesn't have any styling. How can I style the script output to blend well with the existing HTML structure? I tried accessing the output by ID, but couldn't figure it out. <script> ...

Is it feasible to generate a realistic arrow using CSS and then rotate it?

Can a fully functional arrow be created using CSS alone? Here is the method I used to create just the arrowhead: http://jsfiddle.net/2fsoz6ye/ #demo:after { content: ' '; height: 0; position: absolute; width: 0; border: 10p ...

Handling web driver timeouts using try/except statements in Python

When attempting to open a link to an mp3 file and then close it using driver.get(url), I encountered an issue. The link to Google (http://www.google.com) works fine, but the mp3 link gets stuck at driver.get(url) and won't close. I tried setting a tim ...

Obtaining the entire text from a truncated message displayed on a webpage using Selenium in Java

Is there a way to extract the complete text from a link contained within a page element and retrieve its value using the .getText() parameter? The issue I'm facing is that only a part of the text is displayed on the page, followed by "...". .getText ...

Encountering a Broken Pipe Error when using Selenium in conjunction with the ChromeDriver

While attempting to scrape a website's index page and locate an element containing login text, I ran the following code: from selenium import webdriver import os chromedriver = "/usr/bin/chromedriver" os.environ["webdriver.chrome.driver"] = chromedr ...

Guide to creating an autoplay feature for a CSS slider

I have created a basic HTML/CSS slider with just 2 slides and I'm looking to set it to automatically switch slides every 7 seconds. Since I'm not well-versed in jQuery or JavaScript, I'm hoping for a CSS-based solution... Could you assist m ...