将元素的定位路径保存在properties文件中,如图所示
调用方式如下图代码所示,可以增强代码的可读性
public class Demo16 {
public static void main(String[] args) throws IOException, Exception {
System.setProperty("webdriver.chrome.driver","D:\\chromedriver.exe");
//实例化一个Chrome浏览器的实例
WebDriver driver = new ChromeDriver();
//实例化一个Firefox浏览器的实例
//FirefoxDriver driver = new FirefoxDriver();
driver.get("http://xxxxxxxxxx");
waitTime(1000);
driver.manage().window().maximize();
waitTime(1000);
//Properties文件在包下的读取方式
Properties p=new Properties();
try {
p.load(Demo16.class.getResourceAsStream("Test.properties"));
} catch (IOException e) {
e.printStackTrace();
}
/*
//Properties文件在src目录下的读取方式
Properties p=new Properties();
p.load(Demo16.class.getClassLoader().getResourceAsStream("Test.properties"));
*/
driver.findElement(By.className(p.getProperty("username"))).sendKeys("11111111");
waitTime(1000);
driver.findElement(By.xpath(p.getProperty("password"))).sendKeys("123");
waitTime(1000);
driver.findElement(By.xpath(p.getProperty("login"))).click();
/*
//原始的定位,可读性比较差
driver.findElement(By.className("el-input__inner")).sendKeys("11111111");
waitTime(1000);
driver.findElement(By.xpath(".//*[@id='app']/div/div[2]/div/div/form/div[2]/div/div/input")).sendKeys("123");
waitTime(1000);
driver.findElement(By.xpath(".//*[@id='app']/div/div[2]/div/div/form/div[3]/div/div/button")).click();
*/
}
static public void waitTime(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}