Selenium代码问题:判断元素状态未返回布尔值求助
Selenium中isEnabled()/isSelected()未返回预期布尔值问题解决
问题描述
刚学习Selenium,需要验证输入框和单选框是否启用,同时完成表单填充并点击单选框,但调用isEnabled()和isSelected()方法后,控制台未返回预期的true或false,而是输出了WebElement对象的相关信息。测试网站:https://testautomationpractice.blogspot.com/
原代码
package day26; import org.openqa.selenium.chrome.ChromeDriver; public class Practice { public static void main(String[] args) throws InterruptedException { WebDriver driver=new ChromeDriver(); driver.get("https://testautomationpractice.blogspot.com/"); driver.manage().window().maximize(); System.out.println(driver.getCurrentUrl()); driver.findElement(By.xpath("//input[@id='name']")).sendKeys("Rock"); WebElement rb=driver.findElement(By.xpath("//input[@id='male']")); rb.isEnabled(); System.out.println("Status is:"+rb); rb.click(); System.out.println("click happened"+rb); rb.isSelected(); System.out.println("rb is"+rb); } }
控制台输出
https://testautomationpractice.blogspot.com/ Status is:[[ChromeDriver: chrome on windows (48d0996f15a36fae8d911fcdbd7ef153)] -> xpath: //input[@id='male']] click happened[[ChromeDriver: chrome on windows (48d0996f15a36fae8d911fcdbd7ef153)] -> xpath: //input[@id='male']] rb is[[ChromeDriver: chrome on windows (48d0996f15a36fae8d911fcdbd7ef153)] -> xpath: //input[@id='male']]
问题原因与解决方案
问题出在你只是调用了isEnabled()和isSelected()方法,但没有将这两个方法返回的布尔值(true/false)输出,反而直接打印了WebElement对象rb,所以控制台显示的是对象的toString信息。
修改代码时,需要直接输出方法的返回值,而不是输出对象本身。修改后的代码如下:
package day26; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class Practice { public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.get("https://testautomationpractice.blogspot.com/"); driver.manage().window().maximize(); System.out.println(driver.getCurrentUrl()); // 填充输入框 driver.findElement(By.xpath("//input[@id='name']")).sendKeys("Rock"); WebElement rb = driver.findElement(By.xpath("//input[@id='male']")); // 输出isEnabled()的返回值 System.out.println("Status is:" + rb.isEnabled()); rb.click(); System.out.println("click happened"); // 输出isSelected()的返回值 System.out.println("rb is selected: " + rb.isSelected()); // 可选:关闭浏览器 driver.quit(); } }
关键修改点
- 将
System.out.println("Status is:"+rb);改为System.out.println("Status is:" + rb.isEnabled());,直接获取并打印元素的启用状态 - 将
System.out.println("rb is"+rb);改为System.out.println("rb is selected: " + rb.isSelected());,打印元素的选中状态 - 补充了缺失的导入语句(原代码缺少
By、WebDriver、WebElement的导入,运行时会报错)
修改后运行,控制台会输出预期的true或false结果。
内容的提问来源于stack exchange,提问作者ashutosh rai
相关产品推荐
相关产品推荐

