selenium 代码中的 isSelected() 方法 return false
isSelected() method return false in selenium code
我正在尝试测试是否选择了 ROUND TRIP。我可以看到 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());
}
}
ID 为 round_trip_button1
的元素是一个 a
元素,但您需要一个实际 input
且类型为 radio
的元素:
f.findElement(By.cssSelector("a#round_trip_button1 input[type=radio]"));
UPD:要遵循@aberry 的回答 - 您需要检查 a
标签是否有 active
class。定义一个 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);
}
并使用它:
hasClass(f.findElement(By.id("round_trip_button1")), 'active');
isSelected() 适用于输入
复选框、select和单选按钮中的选项。
但在您的情况下,它是通过 'a'(锚文本)实现的,因此默认的 isSelected() 将不起作用。
对于你的情况,我检查了 'a' 属性,你可以通过检查 class 值 'active' 轻松自定义实现 isSelected() 方法。
当 round_trip_button1 id 被 selected 时,它的 class 包含字符串 'active' 并且其他大小写 'active' 丢失。
我正在尝试测试是否选择了 ROUND TRIP。我可以看到 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());
}
}
ID 为 round_trip_button1
的元素是一个 a
元素,但您需要一个实际 input
且类型为 radio
的元素:
f.findElement(By.cssSelector("a#round_trip_button1 input[type=radio]"));
UPD:要遵循@aberry 的回答 - 您需要检查 a
标签是否有 active
class。定义一个 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);
}
并使用它:
hasClass(f.findElement(By.id("round_trip_button1")), 'active');
isSelected() 适用于输入 复选框、select和单选按钮中的选项。
但在您的情况下,它是通过 'a'(锚文本)实现的,因此默认的 isSelected() 将不起作用。
对于你的情况,我检查了 'a' 属性,你可以通过检查 class 值 'active' 轻松自定义实现 isSelected() 方法。 当 round_trip_button1 id 被 selected 时,它的 class 包含字符串 'active' 并且其他大小写 'active' 丢失。