How can I get all elements from drop down list in Selenium WebDriver?

前端 未结 11 2047
遥遥无期
遥遥无期 2020-12-11 06:10

How can I get all elements from a drop down list? I used the code below:

List elements = driver.findElements(By.id(\"s\"));
11条回答
  •  醉梦人生
    2020-12-11 06:27

    There are multiple approaches to print the texts from the option elements of a drop-down-menu. Ideally while interacting with a html-select element you need to use the Select Class. Further to interact with the tags you need to use getOptions() method.


    Demonstration

    As an example to print the texts from the Day, Month and Year option elements within facebook landing page https://www.facebook.com/ you need to induce WebDriverWait for the elementToBeClickable() and you can use the following Locator Strategies.


    Options from Day Dropdown

    Using id attribute:

    • Code Block:

      WebElement dayElement = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.id("day")));
      Select selectDay = new Select(dayElement);
      List dayList = selectDay.getOptions();
      for (int i=0; i

    Options from Month Dropdown

    Using xpath and java-8 stream() and map():

    • Code Block:

      Select selectMonth = new Select(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//select[@id='month']"))));
      List myMonths = selectMonth.getOptions().stream().map(element->element.getText()).collect(Collectors.toList());
      System.out.println(myMonths);
      
    • Console Output:

      [Month, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sept, Oct, Nov, Dec]
      

    Options from Year Dropdown using a single line of code

    Using [tag:css_selectors] and java-8 stream() and map() in a single line of code:

    • Line of code:

      System.out.println(new Select(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("select#year")))).getOptions().stream().map(element->element.getText()).collect(Collectors.toList()));
      
    • Console Output:

      [Year, 2020, 2019, 2018, 2017, 2016, 2015, 2014, 2013, 2012, 2011, 2010, 2009, 2008, 2007, 2006, 2005, 2004, 2003, 2002, 2001, 2000, 1999, 1998, 1997, 1996, 1995, 1994, 1993, 1992, 1991, 1990, 1989, 1988, 1987, 1986, 1985, 1984, 1983, 1982, 1981, 1980, 1979, 1978, 1977, 1976, 1975, 1974, 1973, 1972, 1971, 1970, 1969, 1968, 1967, 1966, 1965, 1964, 1963, 1962, 1961, 1960, 1959, 1958, 1957, 1956, 1955, 1954, 1953, 1952, 1951, 1950, 1949, 1948, 1947, 1946, 1945, 1944, 1943, 1942, 1941, 1940, 1939, 1938, 1937, 1936, 1935, 1934, 1933, 1932, 1931, 1930, 1929, 1928, 1927, 1926, 1925, 1924, 1923, 1922, 1921, 1920, 1919, 1918, 1917, 1916, 1915, 1914, 1913, 1912, 1911, 1910, 1909, 1908, 1907, 1906, 1905]
      

提交回复
热议问题