【发布时间】:2014-06-24 14:02:55
【问题描述】:
我在 C# 中使用 Selenium,我需要能够根据与该单选按钮关联的标签文本来指定要单击网站上的哪个单选按钮。我需要能够将该文本作为参数传递。以下是单选按钮的代码示例(这是三个按钮):
<input id="radSelect152_222_1369" class="bgRadioNotChecked" type="radio" onclick="BGQ.Ajax.SelectAnswer(this, '152','1369','3', '547');" value="1369" onfocus="BGQ.View.setLastElement(true);" name="radSelect152_222">
<label class="inline" for="radSelect152_222_1369">Watermelon</label>
<input id="radSelect152_222_1370" class="bgRadioNotChecked" type="radio" onclick="BGQ.Ajax.SelectAnswer(this, '152','1370','3', '547');" value="1370" onfocus="BGQ.View.setLastElement(true);" name="radSelect152_222">
<label class="inline" for="radSelect152_222_1370">Papaya</label>
<input id="radSelect152_222_1371" class="bgRadioNotChecked" type="radio" onclick="BGQ.Ajax.SelectAnswer(this, '152','1371','3', '547');" value="1371" onfocus="BGQ.View.setLastElement(true);" name="radSelect152_222">
<label class="inline" for="radSelect152_222_1371">Mango</label>
我希望能够在 Excel 输入文件中指定“Mango”(我的所有文件输入内容都可以正常工作)并让 Selenium 单击相关的单选按钮。我读到的我一直在尝试的一种方法是执行以下操作:
- 查找以目标文本(“Mango”)为文本的元素
- 从该元素获取 FOR 属性
- 查找 id 等于该 FOR 属性的输入
- 单击该输入元素。
问题是,我对 Selenium 还很陌生,不太了解如何执行这四个步骤的语法。有人可以用具体的代码示例告诉我方法吗?另外,或者,是否有更好/更智能的方法来做到这一点?如果有,请具体说明。
我在这里包含了我开始编写的方法,我在其中传递了目标文本。我知道这是错误的(尤其是在 By.XPath 部分)。
public void ClickRadioButtonByLabelText(string labelText)
{
// (1) Find the element that has the label text as its text
IWebElement labelForButton = commondriver.FindElement(By.XPath(//label[text()='labelText']));
// (2) Get the FOR attribute from that element
string forAttribute
// (3) Find the input that has an id equal to that FOR attribute
// (4) Click that input element
}
谢谢。
【问题讨论】:
-
为什么不点击标签?因为它们是通过
for属性连接的,所以应该选中相关的复选框。
标签: c# html selenium automation