[英]How can I locate value from dropdown in C# selenium?
How Can i select value "bb" from the dropdown without using XPath.我如何在不使用 XPath 的情况下从下拉列表中获取 select 值“bb”。 The code is代码是
First Dropdown第一个下拉菜单
<div class="col-sm-4 col-md-4 col-lg-4">
<div class="form-label-group">
<select class="custom-select">
<option value="" selected="selected">-- Select --</option>
<option value="09">
dd
</option>
<option value="08">
ee
</option>
<option value="07">
ff
</option>
</select>
<label for="Teacher">person</label>
</div>
</div>
Second DropDown第二个下拉
<div class="col-sm-4 col-md-4 col-lg-4">
<div class="form-label-group">
<select class="custom-select">
<option value="" selected="selected">-- Select --</option>
<option value="01">
aa
</option>
<option value="02">
bb
</option>
<option value="03">
cc
</option>
</select>
<label for="profile">student</label>
</div>
</div>
I want to select value bb from second dropdown.我想从第二个下拉列表中获取 select 值 bb。 When code runs it goes to first dropdown and cannot find value bb and fails.当代码运行时,它会进入第一个下拉列表,找不到值 bb 并失败。 How can I do that?我怎样才能做到这一点?
Dom contains two dropdown with same class but different label so we can differ the dropdowns using the label Dom 包含两个具有相同 class 但不同 label 的下拉列表,因此我们可以使用 label 来区分下拉列表
Xpath for label Teacher: //label[@for="Teacher"]//ancestor::div//select
Xpath for label 老师: //label[@for="Teacher"]//ancestor::div//select
Xpath for label profile: //label[@for="profile"]//ancestor::div//select
Xpath 用于 label 配置文件: //label[@for="profile"]//ancestor::div//select
Now You can use select class for the dropdown's现在您可以使用select class 作为下拉菜单
var student_drpdwn= driver.FindElement(By.xpath("//label[@for="Teacher"]//ancestor::div//select"));
var person_drpdwn= driver.FindElement(By.xpath("//label[@for="profile"]//ancestor::div//select"));
//Initialize class select with student_drpdwn webelement object
var select_person=new Select(person_drpdwn);
var select_student=new Select(student_drpdwn);
//select by value
select_person.selectByValue("09");
select_student.selectByValue("01");
// select by text
select_person.SelectByText("dd");
select_student.SelectByText("aa");
Identify your drop down By Xpath:通过 Xpath 识别您的下拉列表:
var student = driver.FindElement(By.XPath("//label[text()='student']//ancestor::div//select"))
By CSS Selector:通过 CSS 选择器:
var student = driver.FindElement(By.CssSelector(".custom-select:nth-of-type(2)")) # As student is second drop down on page with class name as custom-select
Now, create select type现在,创建 select 类型
var selectStudent = new SelectElement(student);
//select by value
selectStudent.SelectByValue("02");
// select by text
selectStudent.SelectByText("bb");
//Select By Index. Index start at 0, so aa-0, bb-1
selectStudent.SelectByIndex(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.