select randomly from dropdown list?

大城市里の小女人 提交于 2021-02-08 04:51:16

问题


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();

回答1:


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();
}



回答2:


// Locate the dropdown menu
WebElement drpdown = driver.findElements(By.id("id of the dropdown menu"));

// click the dropdown menu
drpdown.click();

//Get the list of dropdown options
List<WebElement> itemsInDropdown = driver.findElements(By.id("id of the dropdown list"));

// Get the size of dropdown list
int size = itemsInDropdown.size();

// Generate the random number
int randomNumber = ThreadLocalRandom.current().nextInt(0, size);

// Clicking on random value
itemsInDropdown.get(randomNumber).click();


来源:https://stackoverflow.com/questions/44587164/select-randomly-from-dropdown-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!