selenium java
package chen;
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;
/**
* @description:
* @author: 淡
* @createDate: 2021-02-04 18:06
* @version: 1.0
*/
public class Itest {
public static void main(String[] args) throws InterruptedException {
//这里,我电脑配置了环境变量,所以就不用在代码里手动配置浏览器驱动了
//设置chromedriver地址
//System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\Google\\Chrome\\Application\\chromedriver.exe");
//账号填写框、密码填写框、以及登录按钮的Xpath
String IdXpath = "//*[@id=\"loginName\"]";
String PasswordXpath = "//*[@id=\"password\"]";
String ButtonLoginXpath = "//*[@id=\"account-login\"]/form/button";
//账号、密码
String Id = "你的账号";
String Password = "你的密码";
//创建一个浏览器窗口
WebDriver driver = new ChromeDriver();
// 隐式等待只能作用于元素的等待。
// 如果元素在指定的时间内找到,则不会继续等待,否则在指定时间内未找到元素则抛出NoSuchElementException。
// 作用域是全局的,跟driver的生命周期一样,一般定义在父类中,只要设置隐式等待后,页面所有的元素都会被绑定这种等待机制,只需设置一次,全局有效(只作用于元素),直到driver实例被关闭。
// 隐式等待等待5秒
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://你要登录的网站的网址/");
System.out.println("Page title is: " + driver.getTitle());
//driver.findElement(By.xpath("//*[@id=\"loginName\"]"));
//根据Xpath寻找对应的
WebElement elementId = driver.findElement(By.xpath(IdXpath));
WebElement elementPassword = driver.findElement(By.xpath(PasswordXpath));
WebElement elementButtonLogin = driver.findElement(By.xpath(ButtonLoginXpath));
//填写账号密码
elementId.sendKeys(Id);
elementPassword.sendKeys(Password);
//输出登录名、密码到控制台,观察是否正确
System.out.println("登录名:" + elementId.getAttribute("value"));
System.out.println("登录名:" + elementPassword.getAttribute("value"));
//判断填写的用户名与密码是否正确,正确,则按下登录键
if (elementId.getAttribute("value").equals(Id)
&& elementPassword.getAttribute("value").equals(Password)) {
//点击登录按钮
elementButtonLogin.click();
//我访问的网址的一个功能
//登录后,本页面出现了个按钮,点击这个按钮会进行页面跳转
String ButtonIntoXPath = "//*[@id=\"index-carousel\"]/div[1]/div[2]/a";
WebElement elementButtonInto = driver.findElement(By.xpath(ButtonIntoXPath));
elementButtonInto.click();
}
*[@id="password"]
*[@id="learning-list"]/div/div[2]/a[2]/span
//*[@id="learning-list"]/div/div[2]/a[1]
}
}