使用Selenium,了解如何基于关联的标签单击单选按钮

本文关键字:标签 单击 单选按钮 关联 何基于 Selenium 了解 使用 | 更新日期: 2023-09-27 18:02:23

我在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输入文件(我有所有的文件输入的东西工作良好),并有硒单击相关的单选按钮。我读到我一直在尝试的一种方法是:

  1. 查找以目标文本("Mango")为文本的元素
  2. 从该元素获取FOR属性
  3. 查找id等于FOR属性的输入

问题是,我对Selenium非常陌生,不能完全理解如何执行这四个步骤的语法。有人可以告诉我的方式,具体的代码示例?另外,或者说,是否有更好/更聪明的方法来做到这一点?如果有,请具体说明。

我在这里包含了我开始编写的方法,我在其中传递目标文本。我知道这是不对的(尤其是在旁边)。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
    }

谢谢。

使用Selenium,了解如何基于关联的标签单击单选按钮

您有两个选择。

选项1—在单个XPath查询中完成所有操作

XPath查询应该是:

//input[@id=//label[text()='TestCheckBox']/@for]

即,从具有"TestCheckBox"的textlabel中获取具有来自for属性的idinput

选项2 -从标签中获取属性,然后在单独的步骤中查找元素

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 = labelForButton.GetAttribute("for");
    // (3) Find the input that has an id equal to that FOR attribute
    IWebElement radioElement = commondriver.FindElement(By.Id(forAttribute));
    // (4) Click that input element
    radioElement.Click();
}