2016-02-25 172 views
0

我是Selenium的新手,並試圖處理下拉列表。我無法使.SelectBy方法工作,所以我想我會回到基礎知識,並使用SelectElement.Options方法列出下拉列表的內容。WebDriver SelectElement似乎無法正常工作

我有一個網頁作爲國家的下拉菜單下面的HTML,

<select name="ddlCountry" id=" ddlCountry> 
<option selected="selected" value="0">Please select ...</option> 
<option value="231">United Kingdom</option> 
<option value="1">Afghanistan</option> 
<option value="2">Albania</option> 
... 
<option value="246">Zimbabwe</option> 
</select> 

然後我有以下代碼列出了每個選項的文本。

var dropdown = driver.FindElement(By.Id("phMainContent_EmployeeAdd1_ddlCountry")); 
var selectItem = new SelectElement(dropdown); 
var options = selectItem.Options; 
foreach (var option in options) 
{ 
    Debug.WriteLine(option.Text); 
} 

當我詢問選項變量時,它包含預期選項數的列表。但是,當您查看列表中每個選項的「文本」屬性時,它是空白的!爲什麼?

補充問題我怎麼會列出價值指數每個選項的性質,因爲只有似乎是文本財產?

我希望一旦這是解釋我會知道爲什麼以下不起作用,以選擇列表中的項目。

/// <summary> 
/// WebDriver: Select an element in a dropdown 
/// </summary> 
/// <param name="driver">WebDriver object</param> 
/// <param name="dropdownlist">Name of dropdown (by ID)</param> 
/// <param name="text">Text of item to be selected</param> 
/// <returns>None</returns> 
public static void SelectItemInDropdownByIdByText(IWebDriver driver, string dropdownlist, string text) 
{ 
    var dropdown = driver.FindElement(By.Id(dropdownlist)); 
    var selectItem = new SelectElement(dropdown); 
    selectItem.SelectByValue(text); 
} 

通過

SelectItemInDropdownByIdByText(driver, "ddlCountry", "United Kingdom"); 

回答

0

叫你想

selectItem.SelectByText

你要了解的東西,是<select>的使用價值來確定文本。然而,硒對待這些不同。藉此,例如:

<select id="test"> 
    <option value="1">One</option> 
    <option value="2">Two</option> 
    <option value="3">Three</option> 
</select> 

test = <select id="test">

test.SelectByValue("2") // selects <option value="2"> 
test.SelectByText("Three") // selects <option value="3"> 
test.Options[1].Text // the Text is actually the `textContent` of the node, which is "Two" 
text.Options[0].GetAttribute("value") // 1 
+0

感謝您指出我在正確的方向。我可以使用 - Debug.WriteLine(option.GetAttribute(「value」)+「:」+ option.GetAttribute(「index」)+「:」+ option.GetAttribute(「text」)列出選項屬性。 ; – Cooldudescrib

+0

@sircafpsalot,但是當我嘗試使用SelectByText方法在下拉列表中選擇一個項目時,它失敗了。 var dropdown = driver.FindElement(By.Id(「ddl_Country」));找到選擇。下一行var selectItem = new SelectElement(dropdown);失敗。最終拋出異常「元素當前不可見並且可能不被操縱」。 – Cooldudescrib

+0

我剛剛看了一下代碼(不是我的),我注意到** select **有一個style =「display:none」,這可以解釋爲什麼它不可見被操縱。這是否會成爲SelectElement(下拉)失敗的正當理由?編碼器已經使用了另一個下拉實現,我現在需要弄清楚! – Cooldudescrib

相關問題