How to select a value from drop down in webdriver
Consider the scenario where in a drop down there are 20 items and need to select an item via webdriver.
By using the following code this can be solved
1. WebElement select = driver.findElement(By.id("XYZ"));
2. List<WebElement> alloptions = select.findElements(By.tagName("option"));
3. for(WebElement option: alloptions){
4. System.out.println(String.format("value is:%s", option.getText()));
5. if(option.getText().equalsIgnoreCase("ABC")){
6. option.click();
}
}
By using the following code this can be solved
1. WebElement select = driver.findElement(By.id("XYZ"));
2. List<WebElement> alloptions = select.findElements(By.tagName("option"));
3. for(WebElement option: alloptions){
4. System.out.println(String.format("value is:%s", option.getText()));
5. if(option.getText().equalsIgnoreCase("ABC")){
6. option.click();
}
}
In the above code
line 1: drop down is identified either
by id, by tag name, by name
by id, by tag name, by name
line 2: reading list of all items present in the drop down
line 3: using for loop list items from line 2 passed into webElement
line 4: used to print the content in console
line 5: using If condition if it is success
line 6: click the item.
I follow the above process when need to select a value from drop down.
============================================================== In order to get value instead of text
In line 5 use the below line instead of existing line
if(option.getAttribute("value").equalsIgnoreCase("xyz"){
Note: here xyz is the value
This is useful when your application needs to test in multiple languages where text is different but value remains same.
===============================================================
============================================================== In order to get value instead of text
In line 5 use the below line instead of existing line
if(option.getAttribute("value").equalsIgnoreCase("xyz"){
Note: here xyz is the value
This is useful when your application needs to test in multiple languages where text is different but value remains same.
===============================================================
-----------------------------------------------------------------
Note: The original contents are taken from "http://seleniumhq.org/docs/03_webdriver.html"
Comments