如何使用Selenium WebDriver和Java获取选定的选项

我是Selenium的新手,我被困在这里:

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

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

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

但我所有的努力都是徒劳的任何帮助都将受到赞赏。 提前致谢 :)

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

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

完成答案:

 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); 

在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 

在以下选项上:

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

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

 WebElement option = select.getFirstSelectedOption(); option.getAttribute("value"); 
 var option = driver.FindElement(By.Id("employmentType")); var selectElement = new SelectElement(option); Task.Delay(3000).Wait(); selectElement.SelectByIndex(2); Console.Read();