【问题标题】:How to validate if a radio button is selected or not as per the HTML provided?如何根据提供的 HTML 验证是否选择了单选按钮?
【发布时间】:2019-01-08 22:51:23
【问题描述】:

这是选定单选按钮的 html 代码

<input name="blooms_level" value="4" id="blooms_level4" class="radio " checked="" type="radio">

我尝试了下面的代码,它返回 null

String str = driver.findElement(By.xpath("xpathValue")).getAttribute("checked");
            str.equalsIgnoreCase("true");

请建议任何替代方式,因为检查值为空

【问题讨论】:

  • @checked 是布尔属性。你不需要检查它的值,而只是存在/不存在
  • 如果返回值为空。然后它是未选中的。你检查它是否为 null 而不是 true。 str.equalsIgnoreCase("null")
  • 对于选中的单选按钮,这里的值也为空,因为我在上面给出了 html

标签: java selenium selenium-webdriver xpath css-selectors


【解决方案1】:

你可以做一些简单的事情,比如

Assert.assertTrue(driver.findElement(By.id("blooms_level4")).isSelected(), "Verify checkbox is checked");

TestNG

【讨论】:

    【解决方案2】:

    要验证是否选择了 单选按钮,您可以使用以下任一解决方案:

    if(driver.findElement(By.xpath("//input[@class='radio' and @name='blooms_level'][starts-with(@id,'blooms_level')]")).isSelected())
    //if(driver.findElement(By.cssSelector("input.radio[name='blooms_level'][id^='blooms_level']")).isSelected())
        System.out.println("Radio Button is selected");
    else
        System.out.println("Radio Button is not selected");
    

    【讨论】:

    • 我想验证它是否被选中,如果没有,方法应该失败
    • @Ashwath 要将方法标记为 Fail,您需要使用 Assert,我认为这不是本次讨论的一部分。如果您的要求发生了变化,请随时根据您的新要求提出新问题。 Stackoverflow 志愿者很乐意为您提供帮助。
    • 请参考我原来的问题
    【解决方案3】:

    试试下面提到的 Java 代码:

    Boolean radioSelected= driver.findElement(By.xpath("xpathValue")).isSelected();
         if (radioSelected)
        {
          System.out.println("Radio Button is selected");
        }else{
          System.out.println("Radio Button is not selected");
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-16
      • 2013-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-13
      • 1970-01-01
      相关资源
      最近更新 更多