Selenium教程

Selenium 处理复选框

在本节中,您将学习如何在Selenium Webdriver中处理复选框。
让我们创建一个测试用例,我们将在其中自动执行以下情况:
调用Google chrome浏览器。 导航到您处理该复选框的网站。 从spicejet网站上选中" 高级公民"复选框。 关闭驱动程序。
现在,我们将逐步创建一个测试用例,以使您正确了解如何处理复选框。
步骤1: Eclipse IDE。
第2步: : 右键单击src文件夹,然后单击New>类。
处理复选框 输入班级名称。我提供的类名称为Checkbox_test。 处理复选框
步骤3: 现在,我们将调用Google Chrome浏览器。我们将下载chromedriver.exe文件,并将system属性设置为您的chromedriver.exe文件的路径。
这里是示例代码,用于将system属性设置为chromedriver.exe文件的路径。
System.setProperty("webdriver.chrome.driver","C:\\\\work\\\\chromedriver.exe);
这是调用Google chrome浏览器的示例代码。
WebDriver driver = new ChromeDriver();
结合以上两个代码块,我们将获得代码片段以启动Google chrome浏览器。
// Set the system property
System.setProperty("webdriver.chrome.driver","C:\\\\work\\\\chromedriver.exe);
// Launch the Google Chrome browser.
WebDriver driver = new ChromeDriver();
第4步: : 第一个测试用例已经完成,即调用了Google chrome浏览器。现在,我们将编写代码以自动化测试用例。我们的第二个测试用例是导航到" spicejet"网站。
以下是示例代码,导航至" spicejet"网站。
    driver.navigate().to("https://www.spicejet.com/");
这是完整的代码:
package mypack;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Checkbox_test {
    public static void main(String[] args) {
        // TOdo Auto-generated method stub
        System.setProperty("webdriver.chrome.driver","C:\\\\work\\\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.navigate().to("https://www.spicejet.com/");
    }}
第5步: 现在,我们尝试通过检查其HTML代码来查找"老年人"复选框。
处理复选框
请注意复选框的id属性。
处理复选框
在上述情况下,我们观察到'id'是唯一属性,因此我们使用 id定位该复选框属性。
第6步: 要使第三个测试用例自动化,我们需要编写代码来定位" 高级公民"复选框。
以下是用于处理"老年人"复选框的代码。
package mypack;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Checkbox_test 
{
public static void main(String[] args) 
{
        // TOdo Auto-generated method stub
        System.setProperty("webdriver.chrome.driver","C:\\\\work\\\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.navigate().to("https://www.spicejet.com/");
        System.out.println(driver.findElement(By.cssSelector("input[id*='SeniorCitizenDiscount']")).isSelected());
        driver.findElement(By.cssSelector("input[id*='SeniorCitizenDiscount']")).click();
        System.out.println(driver.findElement(By.cssSelector("input[id*='SeniorCitizenDiscount']")).isSelected());
driver.close();
    }
}
在上面的代码中,我们没有使用完整的'id'属性值,因为它非常大。我已经使用了"高级公民"复选框的一半,而另一半则以正则表达式的形式表示,即" * ="。
在上面的代码中我们使用了两种方法:
isSelected(): : 此方法确定是否选中该复选框。如果选中此复选框,则此方法返回true,否则返回false。 click(): : 此方法选择定位器。在这种情况下,它将选中"高级公民"复选框。
输出
处理复选框
控制台上的输出
处理复选框
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4