2012-08-13 29 views
23

我在硒新手的選擇,我堅持在這裏:如何獲得選擇使用硒的webdriver與Java

我想獲得使用硒的webdriver然後下拉的選擇標籤或價值print it on console

我可以從下拉列表中選擇任何值,但我無法檢索所選值並將其打印出來。

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

但是我所有的努力白費 去任何幫助,將不勝感激。感謝提前:)

回答

40

你應該能夠得到使用getText()(該選項元素你有使用​​)文字:完成了答案

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

我想補充的將來的讀者,我們需要導入org.openqa.selenium.support.ui.Select工作選擇元素。 – Michal 2013-09-05 08:34:53

+0

是的,米歇爾,你是對的。 – 2018-01-09 07:29:44

16

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

硒它是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 
0
var option = driver.FindElement(By.Id("employmentType")); 
     var selectElement = new SelectElement(option); 
     Task.Delay(3000).Wait(); 
     selectElement.SelectByIndex(2); 
     Console.Read(); 
+1

雖然此代碼片段可能會解決問題,但[包括解釋](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 – DimaSan 2016-12-08 09:58:11

1

在以下幾個選項:

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

如果從getText()你得到一個空白的方法,你可以使用方法getAttribute得到期權的價值字符串:

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