02 脚本重构by封装

在这里插入图片描述
在这里插入图片描述

  1. 定位元素和值分开定义
    在这里插入图片描述
  2. 封装By方法
    在这里插入图片描述
    则之前的定位写法:
    在这里插入图片描述
    可更改为:
    在这里插入图片描述
    ok,整个禅道代码更改如下:
    package com.aliyun.chandao;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;

public class LoginV2 {
public WebDriver driver;

public void InitDriver() {
	// 指定chrome driver的获取地址
	System.setProperty("webdriver.chrome.driver", "D:\\BrowserDriver\\chromedriver.exe");

	// 去掉chrome正受到自动测试软件控制信息栏显示
	ChromeOptions options = new ChromeOptions();
	options.addArguments("disable-infobars");

	// 实例化webdriver的对象,启动谷歌浏览器
	driver = new ChromeDriver(options);
	driver.manage().window().maximize();

	// 打开阿里云禅道地址
	driver.get("XXX/zentao");
}

/*
 * 登录脚本
 */
public void loginScript() throws InterruptedException {
	this.InitDriver();
	String username = "XXX";
	String userElement = "account";
	String userBy = "id";
	String userPwd = "XXX";
	String pwdElement = "password";
	String pwdBy = "name";
	String loginButtonElement = "submit";
	String loginButtonBy = "id";

// WebElement user = driver.findElement(By.id(“account”));
WebElement user = driver.findElement(this.byStr(userBy, userElement));
user.isDisplayed();
WebElement password = driver.findElement(this.byStr(pwdBy, pwdElement));
password.isDisplayed();
WebElement loginButton = driver.findElement(this.byStr(loginButtonBy, loginButtonElement));
loginButton.isDisplayed();
user.sendKeys(username);
password.sendKeys(userPwd);
loginButton.click();
Thread.sleep(1000);
// 获取左上角登录用户名的文本并却所有空格,包括首尾、中间
String userInfo = driver.findElement(By.id(“myname”)).getText().replace(" “, “”);;
System.out.println(”>>>" + userInfo);
if(userInfo.equals(“刘斌宇”)){
System.out.println(userInfo + " 登陆成功");
}else{
System.out.println(userInfo + " 登陆失败");

	}
	driver.close();
}

/*
 * 封装By
 */
public By byStr(String by, String local) {
	if(by.equals("id")) {
		return By.id(local);
	}else if(by.equals("name")) {
		return By.name(local);
	}else if(by.equals("className")) {
		return By.className(local);
	}else {
		return By.xpath(local);
	}
}

public static void main(String[] args) throws InterruptedException {
	LoginV2 login = new LoginV2();
	login.loginScript();
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值