selenium实战:登录网站

实现功能如下:

1.  通过id定位,用户名输入框、密码输入框、登录按钮

2. 登录后实现一个xpath索引定位

代码如下:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;


public class LoginCnBlogs {

    public static void main(String[] args) {
        //指定chrome驱动
        System.setProperty("webdriver.chrome.driver", "C:\\drivers\\chromedriver.exe");
        //调用Login方法
        Login();
    }

    /**
     * 登录CNBlogs
     */

    public static void Login() {
        WebDriver driver = new ChromeDriver();
        String Url2 = "https://home.cnblogs.com/set/profile";
        driver.get(Url2);
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        //通过id定位用户名输入框,并输入用户名
        WebElement name = driver.findElement(By.id("mat-input-0"));
        name.sendKeys("username");
        //通过id定位密码输入框,并输入密码
        WebElement PassWord = driver.findElement(By.id("mat-input-1"));
        PassWord.sendKeys("password");
        //通过id定位密登录按钮,并点击登录
        WebElement login = driver.findElement(By.tagName("button"));
        login.click();

        //登录后如果需要定位,一定要页面等待,否则会报错
        try {
            //页面等待
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //索引定位ul下多个同等级的li,选择第4个
        WebElement option = driver.findElement(By.xpath("//ul[@class = 'app_list']/li[4]"));
        option.click();


    }

}

 

posted @ 2021-08-12 18:03  测试长流  阅读(248)  评论(0)    收藏  举报