【问题标题】:Trying to check whether a radio button is checked or not尝试检查单选按钮是否被选中
【发布时间】:2023-03-08 20:22:01
【问题描述】:

我正在尝试检查网站http://www.makemytrip.com/上是否选中了单选按钮,但它总是显示为false。

public static void cBoxRbtnDd () throws Exception{
    driverGlobal.get("http://www.makemytrip.com/");
    driverGlobal.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

    String rdBtn = ".//*[@id='one_way_button1']/span";
    boolean att = driverGlobal.findElement(By.xpath(rdBtn)).isSelected();
    System.out.println(att);

    driverGlobal.findElement(By.xpath(rdBtn)).click();

    WebElement radioBtn = driverGlobal.findElement(By.xpath(rdBtn));
    new WebDriverWait(driverGlobal,10).until(ExpectedConditions.visibilityOf(radioBtn));

    boolean att1 = driverGlobal.findElement(By.xpath(rdBtn)).isSelected();
    System.out.println(att1);   
}

【问题讨论】:

    标签: java selenium xpath selenium-webdriver


    【解决方案1】:

    单选按钮通常使用<input> 和属性type="radio" 创建。如果您注意到网站上的单选按钮,他们实际上是在使用<a> 标签和 DOM 操作来创建单选按钮。

    单选按钮被选中的效果是由 CSS 完成的。注意,选中的单选按钮有一个类active。因此,您需要检查该类是否包含值active 以了解它是否已被选中。

    你可以使用下面给出的代码sn-p:

    public boolean ifActive(WebElement element) {
        String classes = element.getAttribute("class");
        return classes.contains("active");
    }
    ifActive(driverGlobal.findElement(By.id("one_way_button1")));    //false
    ifActive(driverGlobal.findElement(By.id("round_trip_button1"))); //true
    ifActive(driverGlobal.findElement(By.id("multi_city_button")));  //false
    

    cmets 中的值是函数将返回的值。请注意,makemyrtip.com 最初默认选择往返单选按钮。

    【讨论】:

    • 亲爱的 Jason Estibeiro 感谢您的回答。我会尽力让你知道。再次感谢您的宝贵时间。
    • @Selenium-Help - 太棒了!请给它一个绿色的勾号。
    猜你喜欢
    • 2014-02-06
    • 2014-04-23
    • 2014-07-02
    • 2016-01-11
    • 2012-06-18
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多