select randomly from dropdown list?

11,784

Selenium is not my thing but

List<WebElement> options = driver.findElements(By.xpath("//*[@role='menu']"));

This will return a list of WebElement match your request. So you should get the element (should be only one I guess) to work with it. You could also use findElement I guess.

Then, you will need to get every Option in the select you have.

List<WebElement> selects = driver.findElements(By.xpath("//*[@role='menu']"));
Random rand = new Random();
for(WebElement select : selects){
    List<WebElement> options = // get every option in it
    int list = rand.nextInt(options.size());
    options.get(list).click();
}
Share:
11,784
User
Author by

User

Updated on June 04, 2022

Comments

  • User
    User about 2 years

    My html sample code is,

     <div class="list">
        <div class="dropdown">
            <ul role="menu">
                <li class="rsbListItem">one</li>
                <li class="rsbListItem">two</li>
                <li class="rsbListItem">three</li>
                <li class="rsbListItem">four</li>
                <li class="rsbListItem">five</li>
                <li class="rsbListItem">six</li>
                <li class="rsbListItem">seven</li>
                <li class="rsbListItem">eight</li>
            </ul>
        </div>
    </div>
    

    How can i write Selenium scripts for this, and each time when i run it should select randomly.

    I have tried to pick random elements,but it's selecting the same element each time. Here is my code.

    List<WebElement> options = driver.findElements(By.xpath("//*[@role='menu']"));
    Random rand = new Random();
    int list= rand.nextInt(options.size());
    options.get(list).click();
    
  • User
    User about 7 years
    When i use 'getOptions()' to get all the options from the dropdown , i need to use 'Select' . But 'Select' is used only in 'select' tagname, for other tagname like 'div' or 'ul' it shows me an error like org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "div"
  • AxelH
    AxelH about 7 years
    @User I can't really help more, I don't use Selenium myself. But in HTML, a dropdown is create like <select><option></option></select>. Not with <ul><li></li></ul> This might be your first mistake.
  • Anantha Raju C
    Anantha Raju C about 5 years
    Adding explanation to your answer would help
  • double-beep
    double-beep about 5 years
    While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.