20. Get Values from Dropdown

Get Values from Dropdown (Birthday field in Gmail registration)
Below is the sample script to get values or options from a dropdown.

Below is the image of Birth Month dropdown




The Birth Month field is not a Drop down. If you want to get all the values from dropdown first we need to click on the arrow mark and then we can get all the values of dropdown.

Here in the below example. First click on the drop down arrow then all the elements (Month options) will be visible and then you can get all the values of dropdown.

package Others;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class dropdown {
            public WebDriver driver;
            @BeforeTest
            public void setUp() throws Exception {
                        //Specify the browser
                        System.setProperty("webdriver.chrome.driver", "D:\\Softwares\\chromedriver_win32\\chromedriver.exe");   
                        driver = new ChromeDriver();
                        //declare globally wait
                        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
                        //maximize the window
                        driver.manage().window().maximize();
            }
            @AfterTest
            public void tearDown() throws Exception {
                        //close the browser
                        driver.quit();
            }
            @Test
            public void testGmail_Reg() throws Exception {
                        driver.get("https://accounts.google.com/SignUp");
                        //click on the arrow mark
                        driver.findElement(By.xpath("//label[@id='month-label']/span/div/div")).click();
                        //get all the vlaues of dropdown
                        List<WebElement> x=driver.findElements(By.xpath("//div[@class='goog-menu goog-menu-vertical']/div"));
                        System.out.println("Size of the dropdown : "+x.size());
                        //print dropdown options
                        for (int i = 0; i < x.size(); i++) {
                                    System.out.println(x.get(i).getText());
                        }
                        Thread.sleep(5000);

            }


}

No comments:

Post a Comment