在C#中使用Selenium Webdriver查找按钮组类中的按钮

Mat*_*ttJ 1 c# selenium webdriver selenium-webdriver

我的最终目标是能够在网页上单击"是"或"否".

使用fire bug我可以看到Yes和No按钮位于名为"btn-group"的类中

<div class="btn-group btn-group-default answer-toggle" aria-label="..." role="group">
     <button class="btn ng-pristine ng-valid active btn-secondary ng-touched" btn-radio="true" ng-model="consultation.previousSoundVoid" ng-class="{'btn-secondary': consultation.previousSoundVoid}" type="button">
          Yes
     </button>
     <button class="btn ng-pristine ng-untouched ng-valid" btn-radio="false" ng-model="consultation.previousSoundVoid" ng-class="{'btn-secondary': consultation.previousSoundVoid == false}" type="button">
          No
     </button>
</div>
Run Code Online (Sandbox Code Playgroud)

我想我可以通过XPath找到Element,但我正在努力提高我的Selenium技能.

我希望有一种方法可以先找到"btn-group"类,然后在某种程度上选择Yes或No.

或者能够为"是"和"否"选项创建变量.如果我做:

var button = Driver.Instance.FindElements(By.ClassName("btn"));
Run Code Online (Sandbox Code Playgroud)

它返回21个选项.我找到:

button[15].Text     returns "Yes"
button[16].Text     returns "No"
Run Code Online (Sandbox Code Playgroud)

而不是必须查看所有21个结果并担心索引是否发生变化,我可以通过某种方式按文本搜索结果吗?

Sai*_*fur 5

最好的方法是使用text并识别这些元素,xpath因为它们没有任何唯一的ID

//button[.='Yes']
Run Code Online (Sandbox Code Playgroud)

不顾一切地使用cssSelector

.btn.ng-pristine.ng-valid.active.btn-secondary.ng-touched
Run Code Online (Sandbox Code Playgroud)

因为它是复合类

你也可以nth-child()用css

[role='group']>button:nth-child(1)
Run Code Online (Sandbox Code Playgroud)

2会让你选择文本按钮No