2012-05-11 105 views
0

我想使用java代碼自動化一個測試用例。我使用selenium服務器庫的相同。現在,當我到達某個頁面時,我得到一個下拉框,其中有一定數量的元素。下拉框是稱爲'流派'。現在我想要做的就是點擊我想展開的下拉框,以便在下一步我可以點擊某個特定的項目,例如。搖滾/金屬/流行增添許多上面我試圖自動化但每次我這樣做的時候我拋出同樣的異常:如何使用Selenium WebDriver從Java下拉框中選擇一個項目?

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//*[@id='Genre']"} 

我曾嘗試提供與即By.xpath的各種方法,通過.name,By.id等,但無濟於事。因此,我複製粘貼有關「流派」框的信息供您參考。請指導我使用哪種方法,以便我能夠成功實現我剛剛描述的目標。

查看選擇源時,我強調流派給我:

<td id="genre" width="50%"> 
                   Genre <br><select name="Genre" id="Genre" class="input_boxbbb" onchange="subgener(this.value)"><option value="0000">All</option><option value="26">AIRTEL JINGLE</option><option value="19">ARTISTS</option><option value="27">BATTERY</option><option value="25">BOLLYWOOD</option><option value="28"> 
+0

複製XPath使用螢火蟲給出:// * [@ ID = 「流派」] – Phoenix225

+0

複製HTML給出: \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t流派
<選擇平變化=「subgener(此。值)」類= 「input_boxbbb」 ID = 「體裁」 名稱= 「流派」><選項值= 「0000」>所有<選項值= 「26」> AIRTEL JINGLE<選項值= 「19」>藝術家<選項值= 「27」> BATTERY<選項值= 「25」> BOLLYWOOD<選項值= 「28」> BUSY<選項值= 「10」>舞曲<選項值= 「16」>舞廳 Phoenix225

+0

使用firebug複製CSS路徑給出:html body form table tbody tr td table tbody tr td table tbody tr td table tbody tr td#genre – Phoenix225

回答

0

假設你與工作的webdriver。該driver變量後來被認爲是有效的webdriver例如:

public void selectGenre(String genreName){ 
    Select genres = new Select(driver.findElement(By.id("genre"))); 
    List<WebElement> options = new ArrayList<WebElement>; 
    options = genres.getOptions(); 
    for (WebElement genre:options){ 
     if(genre.getText().equals(genreName)){ 
      genre.click(); 
     } 
    } 
} 
+0

我得到這個異常,當我嘗試你的代碼:異常在線程「主」org.openqa.selenium.support.ui.UnexpectedTagNameException:元素應該已經「選擇」,但是「td」 – Phoenix225

+0

好的嘗試交換鱈魚e到'By.name' –

+0

也聲明只是選擇引發這個錯誤消息:不能實例化類型Select.It但是得到解決時,我說:org.openqa.selenium.support.ui.Select genres = new org.openqa.selenium .support.ui.Select(driver.findElement(By.name( 「類型」))); – Phoenix225

1

好了,所以建議帕維爾的代碼是正確的,應該工作。

我只對此發表了一條評論。 而不是遍歷所有選項手動你可以使用下列操作之一:

genres.selectByIndex(int index) 
genres.selectByValue(String value) 
genres.selectByVisibleText(String text) 

的問題是與HTML,發現你有2個元素具有相同id但不同的情況。

<td id="genre" width="50%"> 
<select name="Genre" id="Genre"> 

這可能會導致窗簾瀏覽器出現問題,並且通常是不好的做法。

如果你控制HTML,我會建議將<td>元素的ID改爲別的,並使用上面的代碼。

,如果你不是一個寫的HTML嘗試使用

Select genre = new Select(driver.findElementBy(By.name("Genre"))) [Notice the Case sensetivity]; 

如果連不行試試這個檢查在頁面中的所有元素<select>,並用它來接你需要的:

List<WebElement> selects = driver.findElementsBy(By.tagName("select")); 
for (WebElement select : selects) { 
    System.out.println(select) 
} 

希望它有助於

相關問題