首页 > 解决方案 > 无法从硒的下拉列表中选择选项

问题描述

我是 selenium 的新手,我发现很难从下拉列表中获取选项,如果班级之间有空格,我也很难获取 className,请帮助我,提前谢谢。

我将 select 与 selectbyindex 一起使用,也使用了 partialvisibletext,但没有任何效果。

这是 HTML 代码

<div class="form-group" xpath="1">
  <label>Source of Info</label>      
 <!-- <select class="form-control flat-control-inner" ng-model="userPersonal.sourceOfInfo.id" required> 
  <option ng-value="0">--Select--</option>          
  <option data-ng-repeat="si in sourceOfInfoList" data-ng-value="{{si.id}}" ng-selected="si.id==userPersonal.sourceOfInfo.id">{{si.name}}</option>                                  
  </select> -->
     <select class="form-control flat-control-inner dateonly ng-valid ng-touched ng-empty ng-dirty ng-valid-parse" ng-model="userPersonal.sourceOfInfo.id" ng-options="si.id as si.name for si in sourceOfInfoList" style="">
      <option value="" class="">--Select--</option>
      <option label="Newspaper" value="number:1">Newspaper</option>
      <option label="Facebook" value="number:2" selected="selected">Facebook</option>
      <option label="Twitter" value="number:3">Twitter</option>
      <option label="Television" value="number:4">Television</option>
      <option label="Others" value="number:5">Others</option>
    </select>   
  </div>

这是我尝试过的

WebElement source_dropdown = driver.findElement(By.xpath("//select[@class='form-control flat-control-inner dateonly ng-valid ng-touched ng-empty ng-dirty ng-valid-parse']"));
Select source = new Select(source_dropdown);
source.selectByIndex(1);

这就是我在控制台中得到的

Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//select[@class='form-control flat-control-inner dateonly ng-valid ng-touched ng-empty ng-dirty ng-valid-parse']"}

标签: javaseleniumselenium-webdriver

解决方案


试试这个来选择与参数匹配的显示文本的选项

//xpath = select[@ng-model='userPersonal.sourceOfInfo.id']
WebElement dropDownListBox = driver.findElement(By.xpath("//select[@ng-model='userPersonal.sourceOfInfo.id']"));
Select clickThis = new Select(dropDownListBox);
clickThis.selectByVisibleText(value);//value is an option visible in dropdown

推荐阅读