Your ultimate guide

Handling Drop Down using Selenium with Java

 

Handling Drop Down:
    isDisplayed(): Determine if an element is displayed or not.
    isEnabled(): Determine if an element is enabled or not.
    
    selectByVisibleText(): This method selects the dropdown based on visible text
    selectByValue(): This method selects the dropdown based on the value attribute.
    selectByIndex(): This method selects the dropdown based on the index number.


.Example:



// First we need to get the main dropdown WebElement (select tag)
WebElement sdropdown = driver.findElement(By.id("tcg"));

// Then create an Object instance for Select Class(Pre-defined Class)
Select dpdown = new Select(sdropdown);

//To select an option by using Visible Text 
dpdown.selectByVisibleText(India);

//dpdown.selectByValue(ind); 
//dpdown.selectByIndex(4);





isMultiple():
    We can use this method to ensure whether the specified dropdown is a multi-select dropdown or not. This method returns True when the corresponding dropdown is multi-select. 
    That means In some dropdowns, we can able to select two or more elements at a time. In that situation by using 'isMultiple()' method we can find whether it was a multi-select dropdown or not.

Example Program:

WebElement ele = driver.findElement(By.id("tcg"));
Select s = new Select(ele);

if(s.isMultiple())
{
    System.out.println("The Dropdown is Multi-Select");
}
else
{
    System.out.println("The Dropdown is not Multi-Select");
}

getOptions():
    We can use this method to get all options in the specified dropdown.

Example Program:(To print all options in the dropdown)

{
    WebElement ele = driver.findElement(By.id("tcg"));
    Select s = new Select(ele);

    List<WebElement> l = s.getOptions();
    int size = l.size();
    for(int i=0; i<size; i++)
    {
        String options = l.get(i).getText();
        System.out.println(options);
    }
}

- Next Page: MouseOver and Drag-Drop

No comments:

Post a Comment