首页 > 解决方案 > 在 selenium C# 中面临来自 html 表单的问题和选择下拉值

问题描述

我在 selenium C# 中面临来自 html 表单的问题和选择下拉值

我尝试了很多,但每次我收到“无法找到元素”的错误

HTML 表单

<div class="ui-store-assign-role ng-scope">
    <div class="ui-assign-label">
        <h3>Assign Role</h3>
        <span ng-model="vm.viewModel.restrictToBol" ng-click="vm.restrictSellerPermissions(!vm.viewModel.restrictToBol,1)" class="ng-pristine ng-untouched ng-valid"><!-- ngIf: vm.viewModel.restrictToBol --><span ng-if="vm.viewModel.restrictToBol" class="ng-scope">Release from</span><!-- end ngIf: vm.viewModel.restrictToBol --><!-- ngIf: !vm.viewModel.restrictToBol --> BOL</span>
    </div>
    <div class="ui-assign-role-tags">
        <!-- ngRepeat: customerRole in vm.viewModel.userRoles --><div ng-repeat="customerRole in vm.viewModel.userRoles" class="ng-scope">
            <span class="ng-binding">Wholesalers <em class="fa fa-close" data-toggle="modal" data-target="#deleteCustomerRole" data-ng-click="vm.ShowDeleteConfirmationForCustomerRole(customerRole.Id,customerRole.RoleType)"></em></span>
        </div><!-- end ngRepeat: customerRole in vm.viewModel.userRoles -->
    </div>
    <select class="form-control ng-pristine ng-valid ng-touched" name="userRoles" ng-model="vm.viewModel.selectedRoleType" ng-options="role for role in vm.viewModel.roleTypes" ng-change="vm.addCustomerRole()"><option value="" class="" selected="selected">--- Select customer role ---</option><option label="Affiliate" value="string:Affiliate">Affiliate</option><option label="Designer" value="string:Designer">Designer</option><option label="ContestAdmin" value="string:ContestAdmin">ContestAdmin</option><option label="DesignAdmin" value="string:DesignAdmin">DesignAdmin</option><option label="Seller" value="string:Seller">Seller</option><option label="TemplateSeller" value="string:TemplateSeller">TemplateSeller</option></select>
</div>

元素尝试:

dropdown_CustomerRole = //*[@name='userRoles']
Driver.SetDropdownValue(dropdown_CustomerRole, "Seller");

标签: c#selenium-webdriverxpath

解决方案


首先,您需要导入 OpenQA.Selenium.Support.UI,然后这里是选择/下拉列表的处理方式

// select the drop down list
// by xpath
 IWebElement education = driver.FindElement(By.XPath("//*[@name='userRoles']"));
// by css
IWebElement education = driver.FindElement(By.CssSelector("select[name='userRoles']"));
 //create select element object 
 SelectElement selectElement = new SelectElement(education);

 //select by value
 selectElement.SelectByValue("Seller"); 
 // select by text
 selectElement.SelectByText("Seller");

推荐阅读