使用操作类获取下拉值

时间:2017-08-02 08:38:05

标签: selenium selenium-webdriver action

移动到下拉列表中的值后,我想使用actions类来获取它。以下是我写的代码。我正在尝试打印下拉值。输入下拉列表的HTML标签(对于选择我有代码)。请帮帮我

public static void caseSearch()
{
    try
    {
        Actions a=new Actions(driver);
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        logger.info("clicking on cases tab :: ");
        driver.findElement(By.xpath(loader.getProperty(Constants.CaseTab))).click();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        WebElement ele=driver.findElement(By.xpath(loader.getProperty(Constants.CaseSearch)));
        ele.click();
        for(int i=0;i<=20;i++)
        {
            //i want to print the first value of dropdown in console
            a.sendKeys(Keys.DOWN,Keys.DOWN,Keys.DOWN).build().perform();
            String value=ele.getText();
            System.out.println("value is = "+value);
            a.sendKeys(Keys.DOWN,Keys.DOWN).build().perform();
            Thread.sleep(3000);
            a.sendKeys(Keys.ENTER).build().perform();
    }
    }
    catch(Exception e)
    {
        logger.info("case search method is not executed  :: " +e);
    }

}

1 个答案:

答案 0 :(得分:0)

我认为您忘了从下拉框中获取值。 您需要使用Select Class来获取它。

Actions key = new Actions(browser);

WebElement dropdownElement = this.browser.findElement(By.xpath(“ YOUR DROPDOWN ELEMENT”));

      Select dropOptions = new Select(dropdownElement);
      int elements = dropOptions.getOptions().size();

      for (int i = 0; i < elements; i++) {
           dropdownElement.click();
           if (i > 0) {
                Thread.sleep(1000L);
                key.sendKeys(Keys.DOWN).build().perform();
                Thread.sleep(1000L);
                key.sendKeys(Keys.ENTER).build().perform();
           }
           else {
                Thread.sleep(1000L);
                ActionPerformers.sendActionKey(browser, Keys.ENTER);
           }
           System.out.println("ELEMENT " + i + " -> " + dropOptions.getFirstSelectedOption().getText()); //Here you will get the selected Value...
      }

这只是一个例子,我希望它适合您。