1. 程式人生 > >selenium自動化測試 java 選擇 下拉列表 的一個選項

selenium自動化測試 java 選擇 下拉列表 的一個選項

hmtl程式碼

    <select selected="selected" class="ordername" style="width:120px" name="User[user_type]" id="User_user_type">  

    <option value="0">Please Choose</option>  
    <option value="1" selected="selected">one</option>  
    <option value="2">Advertiser</option>  
    <option value="4">Agent</option>  

    </select> 

方法一:

   Select userSelect=new Select(driver.findElement(By.id("User_user_type")));  
   userSelect.selectByVisibleText("電子 數碼");

方法二:

    WebElement adrOption=driver.findElement(By.cssSelector("#User_user_type option[value='2']"));  
    adrOption.click(); 

注意:

不在上述方法前加driver.findElement(By.id("User_user_type")).click();

否則只展開下拉列表,滑鼠在”電子 數碼“上,但是並不會點選此項。