简体   繁体   English

isSelected()方法在硒代码中返回false

[英]isSelected() method return false in selenium code

I am trying to test whether ROUND TRIP is selected or not. 我正在尝试测试是否选择了ROUND TRIP。 I can see ROUND TRIP is selected but still i am getting output as false why? 我可以看到选择了ROUND TRIP,但是我仍然得到错误的输出,为什么?

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class IsSelected {
public static void main(String[] args) {
    WebDriver f= new FirefoxDriver();
    f.get("http://www.makemytrip.com/");
    WebElement e = f.findElement(By.id("round_trip_button1"));
    System.out.println(e.isSelected());
    System.out.println(e.getText());
    System.out.println(e.isDisplayed());
    System.out.println(e.isEnabled());

    }

} }

The element with round_trip_button1 id is an a element, but you need an actual input with radio type instead: id为round_trip_button1的元素是a元素,但是您需要使用radio类型的实际input

f.findElement(By.cssSelector("a#round_trip_button1 input[type=radio]"));

UPD: to follow @aberry answer - you need to check an a tag to have an active class. UPD:要遵循@aberry的答案-您需要检查a标签才能拥有一个active课堂。 Define a function that would check for an element to have a class : 定义一个函数,函数将检查元素是否具有类

public static bool hasClass(WebElement el, string className) {
    return el.getAttribute("class").split(' ').contains(className);
}

And use it: 并使用它:

hasClass(f.findElement(By.id("round_trip_button1")), 'active');

isSelected() applies to input elements such as checkboxes , options in a select and radio buttons. isSelected()适用于输入元素,例如复选框 ,选择中的选项单选按钮。

But in your case, it is implemented through 'a' (anchor text) so default isSelected() will not work. 但是在您的情况下,它是通过“ a”(锚文本)实现的,因此默认的isSelected()将不起作用。

For your case I checked 'a' properties, you can easily custom implement isSelected() method by checking class value 'active'. 对于您的情况,我检查了'a'属性,可以通过检查类值'active'轻松地自定义实现isSelected()方法。 When round_trip_button1 id is selected, its class contains string 'active' and other case 'active' is missing. 选择round_trip_button1 id时,其类包含字符串'active',而其他情况下'active'则丢失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM