1. 程式人生 > >selenium獲取下拉框中的選中的文字的方式

selenium獲取下拉框中的選中的文字的方式

示例程式碼如下:

<select id="ctl00_MainContentPlaceHolder_NoticeManage1_ddlNoticeType" class="select" name="ctl00 $MainContentPlaceHolder$NoticeManage1$ddlNoticeType">
<option value="0">請選擇</option>
<option value="8">重要訊息</option>
<option value="9">證券要聞</option>
<option value="10">大賽規則</option>
<option value="11">21212</option>
</select>

有多種方式,先定位到選擇框的id,然後再取值

//通過下拉列表中選項的索引選中第二項
  Select selectAge = new Select(dr.findElement(By.id("你要選擇的值id")));
  selectAge.selectByIndex(2);
  
  //通過下拉列表中的選項的value屬性選中這一項
  Select selectShen = new Select(dr.findElement(By.id("你要選擇的值id")));
  selectShen.selectByValue("value值");
  
  //通過下拉列表中選項的可見文字選中
  Select selectTown = new Select(dr.findElement(By.id("你要選擇的值id")));

  selectTown.selectByVisibleText("文字值");

//通過Xpath定位

 Select selectSex = new Select(dr.findElement(By.xpath("//[@id='你要選擇的id的值']/option[2]").click();  //表示定位到該id節點下第2個option元素