java+selenium自动化实践

git+java+selenium+testng +maven+idea

1、git之代码维护(下载、分支切换、上传)

下载命令 "git clone git@github.com:Luna0715/learnmaven.git"
git branch -a 列出所有分支
git branch 查看本地分支
创建分支:git branch <name>
创建+切换分支:git checkout -b <name>
git checkout -b develop origin/develop 切换到develop分支
git branch 验证一下,已经切换到develop分支
再切换回master: git checkout master git branch

git remote add origin git@github.com:Luna0715/GodLikeCourse.git
使用命令 git add . 提交新文件(new)和被修改(modified)文件,不包括被删除(deleted)文件到缓存区
git commit -am "修改代码" 用于提交跟踪过的文件 
git push 将本地分支的更新,推送到远程主机
git push --set-upstream origin develop推送远程不存在的本地分支

更新项目:

1.加一个线上主干git remote add upstream git@github.com:QA/GodLikeCourse.git

2.从主干拉取代码 git pull upstream master

git status
git stash

2、引用testng

import org.testng.annotations.Test;

方法前加注释@Test

3、调试

定位到要断点的源代码行,在源代码所在行前面,单击一下鼠标左键,设置一个断点,以DEBUG的模式运行项目

4、元素定位

xpath常用符号说明:

/表示绝对路径,绝对路径是指从根目录开始

//表示相对路径

.表示当前层

..表示上一层

*表示通配符

@表示属性

[]属性的判断条件表达式

1)driver.findElement(By.linkText("个人中心"))

2)driver.findElement(By.id("mobile1")).sendKeys("13111111111");

3)WebElement confirm = driver.findElement(By.className("confirm-btn"));

4)public static String getusername;

getusername = driver.findElement(By.xpath(".//*[@class='option']/li[1]/a")).getText();

WebElement fenqi = driver.findElement(By.xpath("//span[text()='分期']"));

WebElement CheTu = driver.findElement(By.xpath(".//*[@class='carlist']/ul/li[1]"));

By.xpath(".//*[@class='pop-up-layer' and @style='display: block;']")

5)通过定位到的元素继续定位元素

WebElement productlist = driver.findElement(By.id("FirstPageProductList1"));
List<WebElement> products = productlist.findElements(By.className("list-header-ctr"));
System.out.println("product数量"+products.size());
getText = products.get(0).findElements(By.className("company-name")).get(0).getText();
for (WebElement ele : products) {
    sleep(2);
getText = ele.findElements(By.className("company-name")).get(0).getText();
System.out.println("套餐名称是:" + getText);
}
List<WebElement> SeeInof = productlist.findElements(By.className("col-black"));
SeeInof.get(0).click();
5、页面切换
#不关闭旧窗口
public static void removeHandles(WebDriver driver){
//获取当前页面句柄
String handle = driver.getWindowHandle();
// 获取所有页面的句柄,并循环判断不是当前的句柄
for (String handles : driver.getWindowHandles()) {
if (handles.equals(handle))
continue;
driver.switchTo().window(handles);
}
}
#关闭旧窗口
    public static void removeHandles(WebDriver driver){
//获取win窗口
try {
String [] handles = new String[driver.getWindowHandles().size()];//定义一个空数组,数组大小是打开窗口的数量
driver.getWindowHandles().toArray(handles);//将获取到的句柄集合转换为数组
//here
//driver.switchTo().window(handles[1]);
sleep(2);
//切换到旧窗口
WebDriver handle2 = driver.switchTo().window(handles[0]);
sleep(2);
//关闭旧窗口
handle2.close();
sleep(2);
//切换到新窗口
driver.switchTo().window(handles[1]);
sleep(2);
} catch (ArrayIndexOutOfBoundsException e) {
// TODO: handle exception
System.out.println("浏览器切换窗口异常" + e);
}}
6、截图
1)
if(isElementExist(driver, By.xpath("//*[@id=\"list\"]/aside[1]/div[1]/div[2]/aside[1]/a/img")) ==true ){
    System.out.println("车图元素存在!");
}else{
System.out.println("车图元素未找到,失败图片:" + picturePath);
screenShot(picturePath,driver);//调用失败截图功能;
}
public static void screenShot(String path,WebDriver driver){
//将当前窗口截屏,获得一个File的图片文件对象;
File screenFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//将图片文件对象,保存到指定的路径path里,例如D盘的某个文件夹下。
try {
File file = new File(path); //在指定路径中,创建一个空白的图片文件
FileUtils.copyFile(screenFile,file);//将窗口截屏文件,保存到刚刚创建的空白文件里
} catch (IOException e) {
e.printStackTrace();
}
}
2)
try{
driver.findElement(By.className("logo-sv"));
}catch(Exception e) {
e.printStackTrace();
String tpath="D:\\screenshots\\"+getScreen(driver)+".jpg";
System.out.println("logo元素未找到,失败图片:" +tpath);//调用失败截图功能;
}
public static String getScreen(WebDriver driver) throws Exception{
Date dt = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
File screenshot=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot,new File("D:\\screenshots\\"+sdf.format(dt)+".png"));
return sdf.format(dt);
}
7、校验
1)
if (getusername.equals("135****7172")){
System.out.println("登录成功");
}
else{
System.out.println("登录失败");
}
2)
if(isElementExist(driver, By.xpath(".//*[@class='carlist']/ul/li[1]/div[1]")) == true){
System.out.println("第一个车图元素存在!");
}else{
System.out.println("第一个车图元素未找到!");
}
public static boolean isElementExist(WebDriver driver, By by) {
try {
driver.findElement(by);
return true;
} catch(NoSuchElementException e) {
return false;
}
}

8、用JS方法将滚动条定位到某个元素
WebElement CheTu = driver.findElement(By.xpath(".//*[@class='carlist']/ul/li[1]"));
public static void executeJS(WebDriver driver,WebElement arg) {
    //用JS方法将滚动条定位到xx元素,其中auguments[0]就代表element
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();",arg);
}
9、线程休眠
public static  void sleep(double d) {
try {
d *= 1000;
Thread.sleep((int)d);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
10、捕获异常
try {

} catch (InterruptedException e) {
e.printStackTrace();
}
11、断言
assert getPackagename.contains(getText);
assert driver.getTitle().equals("XXXXXX"); 12、初始化
//将浏览器的驱动程序位置设定为系统属性值:webdriver.chrome.driver
System.setProperty("webdriver.chrome.driver", "D:/selenium/chromedriver.exe");
//启动浏览器
WebDriver driver = new ChromeDriver();
//打开网址
driver.get("https://www.xxxxxx.com/");
//窗口最大化
driver.manage().window().maximize();
// 获取 网页的 title
System.out.println("The testing page title is: " + driver.getTitle());
13、需要引入的包
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.openqa.selenium.JavascriptExecutor;

14、主函数快捷键psvm
15、遍历
示例一:
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.interactions.Actions;
import org.testng.Assert;
import java.util.List;
public class secondtestcase {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","D:\\selenium\\chromedriver.exe");
WebDriver driver =new ChromeDriver();
driver.get("http://www.xxxxxx.com/ ");
WebElement hide = driver.findElement(By.className("newcar-down-box"));
Actions action = new Actions(driver);
action.moveToElement(hide).perform();
WebElement pricecondition = driver.findElement(By.cssSelector("div.models-show-newcar.hide"));
// String pricecondition = driver.findElement(By.xpath("/html/body/div[7]/div[1]/div[2]/div[2]/div[2]/dl[1]/dd/a[1]")).getText();
List<WebElement> price = pricecondition.findElements(By.xpath("dl[1]/dd/a"));
String pricetext[]=new String[]{"3万以下","3-5万","5-8万","8-10万","10-15万","15-20万","20-30万","30-45万","45万以上"};
int count=price.size();
for (int i=0;i<count;i++){
Assert.assertEquals(price.get(i).getText(),pricetext[i]);
String priceconteng[]=new String[count];
priceconteng[i]=price.get(i).getText();
System.out.println(priceconteng[i]);
if (price.get(i).getText().equals(pricetext[i])){
System.out.println("匹配");
}
else {
System.out.println("不匹配");
}
}
}
}
示例二:
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class firsttestcase {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "D:\\selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//System.setProperty("webdriver.chrome.driver", "D:/selenium/chromedriver.exe");
//WebDriver driver = new ChromeDriver();
driver.navigate().to("http://xxx.xxxxxx.com/beijing/budget-b26/?source=2525 ");
WebElement brand_select = driver.findElement(By.className("budget-filter"));
List<WebElement> brand = brand_select.findElements(By.xpath("div[1]/dl/dd/a"));
int count = brand.size();
String b[] = new String[]{"本田", "宝骏", "吉利", "大众", "哈弗", "现代", "五菱", "丰田", "众泰", "更多品牌"};
for (int i = 0; i < count; i++) {
try {
if (brand.get(i).getText().equals(b[i])) {
System.out.println("匹配");
}
} catch (Exception e) {
e.printStackTrace();
String picturePath = "D:\\file.png";
screenShot(picturePath,driver);//调用失败截图功能;
}
}
}
public static void screenShot(String path,WebDriver driver){
//将当前窗口截屏,获得一个File的图片文件对象;
File screenFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//将图片文件对象,保存到指定的路径path里,例如D盘的某个文件夹下。
try {
File file = new File(path); //在指定路径中,创建一个空白的图片文件
FileUtils.copyFile(screenFile,file);//将窗口截屏文件,保存到刚刚创建的空白文件里
} catch (IOException e) {
e.printStackTrace();
}
}
}
示例三:
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.By;
import java.util.List;
public class Demo3 {
public static String getText;
public static String taocan;
public static void main(String[] args) {
//将浏览器的驱动程序位置设定为系统属性值:webdriver.chrome.driver
System.setProperty("webdriver.chrome.driver", "D://Java//chromedriver_win32//chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://xxxxx.xxxxxx.com");
driver.manage().window().maximize();
fenqidetails(driver);
//driver.quit();
}
public static void fenqidetails(WebDriver driver){
sleep(2);
WebElement firstcar = driver.findElement(By.xpath(".//*[@class='carlist']/ul/li[1]"));
firstcar.click();
sleep(2);
if(isElementExist(driver, By.xpath(".//*[@class='pop-up-layer' and @style='display: block;']"))==true){
WebElement confirm = driver.findElement(By.className("confirm-btn"));
confirm.click();
}
//设置显示等待时长:10s
WebDriverWait wait = new WebDriverWait(driver, 10);
//显示等待:标题是否出现
try {
wait.until(ExpectedConditions.titleContains("XXXXXX"));
System.out.println("The testing page title is: " + driver.getTitle());
} catch (NoSuchElementException e) {
e.printStackTrace();
System.out.println("标题没找到");
}
try {
wait.until(ExpectedConditions.presenceOfElementLocated(By.className("search")));
System.out.println("有搜索框");
} catch (NoSuchElementException e) {
e.printStackTrace();
System.out.println("搜索框没找到");
}
// List<WebElement> products = driver.findElements(By.xpath(".//*[@id='FirstPageProductList1']/li"));
WebElement productlist = driver.findElement(By.id("FirstPageProductList1"));
List<WebElement> products = productlist.findElements(By.className("list-header-ctr"));
System.out.println("product数量"+products.size());
for (WebElement ele : products) {
sleep(2);
getText = ele.findElements(By.className("company-name")).get(0).getText();
System.out.println("套餐名称是:" + getText);
}
for (int i = 0; i < 1; i++) {
sleep(2);
List<WebElement> SeeInof = productlist.findElements(By.className("col-black"));
SeeInof.get(i).click();
sleep(2);
removeHandles(driver);
taocan = driver.findElement(By.xpath("//*[@id=\"Content\"]/header/section/div/div[1]/h1")).getText();
System.out.println("套餐名称和机构是:" + taocan);
}
}
public static boolean isElementExist(WebDriver driver, By by) {
try {
driver.findElement(by);
return true;
} catch(NoSuchElementException e) {
return false;
}
}
/**
* 移除窗口
*/
public static void removeHandles(WebDriver driver){
//获取win窗口
try {
String [] handles = new String[driver.getWindowHandles().size()];
driver.getWindowHandles().toArray(handles);
for(int i = 0; i<handles.length;i++)
{
}
//here
driver.switchTo().window(handles[1]);
sleep(2);
WebDriver handle2 = driver.switchTo().window(handles[0]);
// log.info(handle2.getTitle());
sleep(2);
handle2.close();
sleep(2);
//切换到新窗口
driver.switchTo().window(handles[1]);
sleep(2);
} catch (ArrayIndexOutOfBoundsException e) {
// TODO: handle exception
System.out.println("浏览器切换窗口异常" + e);
}
}
public static void sleep(double d) {
try {
d *= 1000;
Thread.sleep((int)d);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
示例四:
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class Demo4 {
String getText;
String getPackagename;
public static String picturePath = "D:\\file.png"; //设置截屏文件所在的路径、和图片的格式:图片保存在C盘下,格式是png
public static void main(String[] args) {
//将浏览器的驱动程序位置设定为系统属性值:webdriver.chrome.driver
System.setProperty("webdriver.chrome.driver", "D://Java//chromedriver_win32//chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://xxxxx.xxxxxx.com/beijing/hafuh6/?source=127");
driver.manage().window().maximize();
sleep(2);
Demo4 a=new Demo4();
a.fenqilist(driver);
a.fenqidetails(driver);
//driver.quit();
}
public void fenqilist(WebDriver driver)
{
//判断资质弹层是否存在
if(isElementExist(driver, By.xpath(".//*[@class='pop-up-layer' and @style='display: block;']"))==true)
{
WebElement confirm = driver.findElement(By.className("confirm-btn"));
confirm.click();
}
sleep(2);
if(isElementExist(driver, By.xpath("//*[@id=\"list\"]/aside[1]/div[1]/div[2]/aside[1]/a/img")) ==true ){
System.out.println("车图元素存在!");
}else{
System.out.println("车图元素未找到,失败图片:" + picturePath);
screenShot(picturePath,driver);//调用失败截图功能;
}
//用JS方法将滚动条定位到xx元素,其中auguments[0]就代表element
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();",driver.findElement(By.className("sort-order")));
WebElement productlist = driver.findElement(By.id("FirstPageProductList1"));
List<WebElement> products = productlist.findElements(By.className("list-header-ctr"));
//getText = products.get(0).findElements(By.className("company-name")).get(0).getText();
getText="123";
System.out.println("第一个套餐的名称是:" + getText);
sleep(2);
List<WebElement> SeeInof = productlist.findElements(By.className("col-black"));
SeeInof.get(0).click();
sleep(2);
removeHandles(driver);
}
public void fenqidetails(WebDriver driver)
{
//getPackagename = driver.findElement(By.xpath("//*[@id=\"Content\"]/header/section/div/div[1]/h1")).getText();
getPackagename="123";
System.out.println("套餐名称是:" + getPackagename);
try{
//assert getPackagename.contains(getText);
assert getPackagename==getText;
System.out.println("Test Pass");
}catch(Exception e){
e.printStackTrace();
}
}
//判断元素是否存在
public static boolean isElementExist(WebDriver driver, By by) {
try {
driver.findElement(by);
return true;
} catch(NoSuchElementException e) {
return false;
}
}
// public static void removeHandles(WebDriver driver){
// //获取win窗口
// try {
// String [] handles = new String[driver.getWindowHandles().size()];//定义一个空数组,数组大小是打开窗口的数量
// driver.getWindowHandles().toArray(handles);//将获取到的句柄集合转换为数组
// //here
// //driver.switchTo().window(handles[1]);
// sleep(2);
// //切换到旧窗口
// WebDriver handle2 = driver.switchTo().window(handles[0]);
// sleep(2);
// //关闭旧窗口
// handle2.close();
// sleep(2);
// //切换到新窗口
// driver.switchTo().window(handles[1]);
// sleep(2);
// } catch (ArrayIndexOutOfBoundsException e) {
// // TODO: handle exception
// System.out.println("浏览器切换窗口异常" + e);
// }
// }
public static void removeHandles(WebDriver driver){
//获取当前页面句柄
String handle = driver.getWindowHandle();
// 获取所有页面的句柄,并循环判断不是当前的句柄
for (String handles : driver.getWindowHandles()) {
if (handles.equals(handle))
continue;
driver.switchTo().window(handles);
}
}
public static void screenShot(String path,WebDriver driver){
//将当前窗口截屏,获得一个File的图片文件对象;
File screenFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//将图片文件对象,保存到指定的路径path里,例如D盘的某个文件夹下。
try {
File file = new File(path); //在指定路径中,创建一个空白的图片文件
FileUtils.copyFile(screenFile,file);//将窗口截屏文件,保存到刚刚创建的空白文件里
} catch (IOException e) {
e.printStackTrace();
}
} public static void sleep(double d) {
try {
d *= 1000;
Thread.sleep((int)d);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
16、经验教训
大小写
包不全
元素定位
语句位置 ctrl+alt+L格式化代码
ctrl+alt+O优化导入



 
上一篇:K8S集群技术


下一篇:Java+Selenium自动化对非输入框的日历或日期控件的处理