【问题标题】:How to get selected option using Selenium WebDriver with Java如何使用 Selenium WebDriver 和 Java 获得选定的选项
【发布时间】:2012-08-09 17:18:54
【问题描述】:

我想使用 Selenium WebDriver获取所选标签下拉列表的值,然后在 控制台上打印

我可以从下拉列表中选择任何值,但我无法检索并打印所选值:

Select select = new 
Select(driver.findElement(By.id("MyDropDown"))).selectByVisibleText(data[11].substring(1 , data[11].length()-1));
WebElement option = select.getFirstSelectedOption();

但是我所有的努力都是徒劳的。如何获得选定的选项?

【问题讨论】:

    标签: java selenium selenium-webdriver webdriver junit4


    【解决方案1】:

    您应该能够使用getText() 获取文本(对于您使用getFirstSelectedOption() 获得的选项元素):

    Select select = new Select(driver.findElement(By.xpath("//select")));
    WebElement option = select.getFirstSelectedOption();
    String defaultItem = option.getText();
    System.out.println(defaultItem );
    

    【讨论】:

    • 我想为未来的读者补充一点,我们需要导入 org.openqa.selenium.support.ui.Select 来处理 Select 元素。
    • getFirstSelectedOption 在未选择任何选项时抛出 org.openqa.selenium.NotFoundException。我建议将此异常作为防御措施。
    【解决方案2】:

    完成答案:

    String selectedOption = new Select(driver.findElement(By.xpath("Type the xpath of the drop-down element"))).getFirstSelectedOption().getText();
    
    Assert.assertEquals("Please select any option...", selectedOption);
    

    【讨论】:

      【解决方案3】:

      在 Selenium Python 中是:

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.support.ui import Select
      
      def get_selected_value_from_drop_down(self):
          try:
              select = Select(WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.ID, 'data_configuration_edit_data_object_tab_details_lb_use_for_match'))))
              return select.first_selected_option.get_attribute("value")
          except NoSuchElementException, e:
              print "Element not found "
              print e
      

      【讨论】:

        【解决方案4】:
        var option = driver.FindElement(By.Id("employmentType"));
                var selectElement = new SelectElement(option);
                Task.Delay(3000).Wait();
                selectElement.SelectByIndex(2);
                Console.Read();
        

        【讨论】:

        • 虽然这段代码 sn-p 可以解决问题,including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
        【解决方案5】:

        关于以下选项:

        WebElement option = select.getFirstSelectedOption();
        option.getText();
        

        如果从方法getText()得到一个空白,你可以使用方法getAttribute从选项的值中得到字符串:

        WebElement option = select.getFirstSelectedOption();
        option.getAttribute("value");
        

        【讨论】:

          猜你喜欢
          • 2015-09-01
          • 1970-01-01
          • 2012-09-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-09
          • 1970-01-01
          相关资源
          最近更新 更多