2010-11-24 68 views
3

我有一個下拉列表,我無法從中選擇項目。我可以遍歷列表中的所有項目並找到我想要的項目,但click()不選擇項目。無法在下拉列表中選擇項目

這是代碼。任何人都可以幫忙嗎?

driver.findElement(By.id("components-multi-select")).findElement(By.className("icon")).click(); 
driver.findElement(By.id("components-suggestions")); 

List<WebElement> componentList = driver.findElements(By.className("aui-list-item")); 
for (WebElement component : componentList){ 
    System.out.println(component.getText()); 
    if (component.getText().contains(newComponent)){ 
     component.click(); 
     break; 
    } 
    else{ 
     System.out.println("not equal"); 
    } 

這是組件下拉列表的html代碼。

<div class="field-group aui-field-componentspicker frother-control-renderer" > 
<label for="components">Component/s</label> 

<div class="ajs-multi-select-placeholder textarea long-field"></div> 

<select class="select hidden " id="components" multiple="multiple" name="components" size="5" data-remove-null-options="true"> 
    <option value="-1"> 
    Unknown 
    </option> 
    <option selected="selected" title="Component 1 - A test component" value="10240"> 
    Component 1 
    </option> 
    <option title="Component 2 - " value="10242"> 
    Component 2 
    </option> 
    <option title="Lee 2 " value="10371"> 
    Lee 2 
    </option> 
    <option title="Roy " value="10370"> 
    Roy 
    </option> 
    <option title="Test Documentation " value="10241"> 
    Test Documentation 
    </option> 
</select> 
+0

你能發佈一個包含列表的html的一部分嗎?看起來這個列表是某種3d方的小部件 – 2010-11-25 12:40:37

回答

0

你應該首先找到你的select元素,然後通過遍歷其option小號

WebElement selectElement = driver.findElement(By.id("components")); 

List<WebElement> componentList = selectElement.findElements(By.tagName("option")); 
for (WebElement component : componentList){ 
    System.out.println(component.getText()); 
    if (component.getText().contains(newComponent)){ 
     component.click(); 
     break; 
    } 
    else{ 
     System.out.println("not equal"); 
    } 
} 
+0

我試過了你的代碼,現在當我到達component.click()時,我得到了元素不可見的錯誤。 – John 2010-12-09 18:30:32

+0

使用您提供的代碼的HTML工作正常。你可以發佈CSS嗎?這是由您的組織開發的小部件還是您使用某些第三方小部件? (Dojo,YUI等) – 2010-12-10 09:46:47

1

我會想象你現在已經看到了這一點,但教程顯示選擇像這樣選擇的一個例子:

WebElement select = driver.findElement(By.xpath("//select")); 
List<WebElement> allOptions = select.findElements(By.tagName("option")); 
for (WebElement option : allOptions) { 
    System.out.println(String.format("Value is: %s", option.getValue())); 
    option.setSelected(); 
} 

所以不是叫單擊要調用的setSelected方法

您也可以使用

Select select = new Select(driver.findElement(By.xpath("//select"))); 
select.deselectAll(); 
select.selectByVisibleText("Edam"); 

此處瞭解詳情:http://seleniumhq.org/docs/09_webdriver.html

,我被你的問題,因爲你發佈一些HTML擁有的選項,但在你的代碼中查找某個元素的列表中仍然迷茫通過不以你的HTML存在的類名。或許你只是想點擊某種下拉菜單,而不是一個選擇框選項..

3
Select comboBox = new Select(webDriver 
     .findElementById(comboBoxId)); 
comboBox.selectByVisibleText(optionText); 
-1

如果你試圖觸發秒的ONSELECT事件目的,你可以使用sendkeys(「\ t)。即模擬從元素中跳出。

相關問題