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优化导入
java+selenium自动化实践的更多相关文章
- java+selenium自动化脚本编写
实训项目:创盟后台管理,页面自动化脚本编写 使用工具:java+selenium 1)java+selenium环境搭建文档 2)创盟项目后台管理系统链接 java+selenium环境搭建 一.Se ...
- java selenium 自动化笔记-不是0基础,至少有java基础
本来今天要学GitHub的,但是在群里问了下小伙伴时被暴击.说我学的东西太多太杂,不是很深入,都是皮毛.哎~自己早深有意识到,因个人能力吧,找的资料都不是很全,加上实际工作没有应用到.所以写一篇sel ...
- Java+Selenium自动化对非输入框的日历或日期控件的处理
如图: 1.问题描述: 在应用selenium实现web自动化时,经常会遇到处理日期控件点击问题,手工很简单,可以一个个点击日期控件选择需要的日期,但自动化执行过程中,完全复制手工这 ...
- Java&Selenium自动化测试之数据驱动
一.摘要 本片博文以四个方式展示自动化测试的数据驱动,数组.CSV.Excel.Mysql 二.TestNG&Csv&Driven package testNGWithDataDriv ...
- Java&Selenium自动化测试之Page Object Model
PO是什么: 1.页面对象模型(PO)是一种设计模式,用来管理维护一组web元素的对象库 2.在PO下,应用程序的每一个页面都有一个对应的page class 3.每一个page class维护着该w ...
- java+selenium自动化遇到confirm弹窗,出现NoAlertPresentException: no alert open
//操作js的confirm弹窗,bool控制是否点击确定,true为点击确定,false为点击取消 public static void OperaterJSOfConfirm(WebDriver ...
- Electorn(桌面应用)自动化测试之Java+selenium实战例子
基于electorn的桌面应用,网上相关资料较少.所有记录一下.使用java+selenium+testng对该类型应用的自动化测试方法. 代码样例 package com.contract.web. ...
- Java+Selenium 3.x 实现Web自动化 - 1.自动化准备
(一)自动化准备 说明:本文主要记录了基于公司现有项目(一个电子商务平台),从0开始实现UI自动化的历程.从准备阶段,部分内容直接省略了基础知识,一切以最终做成自动化项目为目标,难免会有晦涩之处.文章 ...
- Java+selenium+Firefox/ IE/ Chrome主流浏览器自动化环境搭建
一.java+selenium+firefox 1.环境准备:JDK1.8 2.安装firefox浏览器v59 3.下载驱动:https://github.com/mozilla/geckodrive ...
随机推荐
- MongoDB Shell 常用操作命令
MonoDB shell命令操作语法和JavaScript很类似,其实控制台底层的查询语句都是用javascript脚本完成操作的. Ø 数据库 1.Help查看命令提示 help db.help ...
- Python笔记:字典的fromkeys方法创建的初始value同内存地址问题
dict中的fromkeys()函数可以通过一个list来创建一个用同一初始value的dict. d = dict.fromkeys(["苹果", "菠萝"] ...
- CentOS7离线安装TIDB
首先准备一台能够联网,并且操作系统版本与正式版本完全一致的服务器. 安装思路是,通过在线方式获得所有离线安装包,然后导入到正式安装环境中去. yum install -y --downloadonly ...
- [转]access 标准表达式中数据类型不匹配
好久没有用access,今儿遇到一个特别让人无语的问题: access数据表的Date/Time类型的字段,假如字段名为dtime: 如果直接用dtime=‘2013/9/6 10:50:21’,sq ...
- FreeMarker的空值运算符和逻辑运算符
1.空值处理运算符 如果你在模板中使用了变量但是在代码中没有对变量赋值,那么运行生成时会抛出异常.但是有些时候,有的变量确实是null,怎么解决这个问题呢? 判断某变量是否存在:“??” 用法为:va ...
- OpenGL中摄像机矩阵的计算原理
熟悉OpenGL|ES的朋友,可能会经常设置摄像机的view矩阵,iOS中相对较好,已经封装了方向,只需要设置摄像机位置,目标点位置以及UP向量即可.下面先介绍下摄像机view矩阵的计算原理.此处假设 ...
- poi excel超出65536行数限制自动扩展Invalid row number (65536) outside allow
1.xls一个sheet只能装65536行,多余则报错 poi包导出或写入excel超出65536报错: java.lang.IllegalArgumentException: Invalid row ...
- 01.VMware虚拟机上网络连接(network type)的三种模式--bridged、host-only、NAT
VMWare提供了三种工作模式,它们是bridged(桥接模式).NAT(网络地址转换模式)和host-only(主机模式).要想在网络管理和维护中合理应用它们,你就应该先了解一下这三种工作模式. 1 ...
- 利用STM32CubeMX来生成USB_HID_Mouse工程【添加ADC】(1)
现在原来的基础上添加ADC的功能. 现在(利用STM32CubeMX来生成USB_HID_Mouse工程)基础上新增硬件 JoyStick Shield 游戏摇杆扩展板 与STM32F103C8的连接 ...
- Unicode UTF8 UTF16 urlencode base64
Unicode:是一个字符集,每个字符对应一个唯一的unicode编码,一般是16位. UTF8是针对Unicode的编码方式,因为如果每个字符都用unicode的编码存储的话会很浪费空间,比如说as ...