用SELENIUM验证一个新增功能

注:若是页面上的元素找不到,每个操做都给设置一个等待时间,按照须要设置不一样等待时间html

一、建立一个JAVA文件来封装浏览器对象 ,用来定义初始化浏览器,脚本以下:java

package seleniumtest;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class test1 {
	public static  WebDriver openBrowser() {
		// TODO Auto-generated method stub
		
		//System.setProperty("webdriver.gecko.driver","D:/myselenium/geckodriver.exe");
		//WebDriver driver = new FirefoxDriver();
		System.setProperty("webdriver.ie.driver","D:/myselenium/iedriver/IEDriverServer.exe");
		DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
		ieCapabilities.setCapability	(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
		WebDriver driver = new InternetExplorerDriver(ieCapabilities);		
		//WebElement d=driver.findElement(By.name("百度 一下"));
		//d.click();		
		return driver;	
	}
}

 

 

二、新增一个TESTNG.class的JAVA文件,并编写代码以下:web

package seleniumtest;



import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TryTest {
  @Test
  public void firstTest() {
	  WebDriver driver =test1.openBrowser();
	  driver.get("http://soasadmin-stg.paic.com.cn/admin/admin/login.html");
	  driver.manage().window().maximize();
	  driver.findElement(By.className("loginName")).sendKeys("YANLI498");
	  WebElement a=driver.findElement(By.className("loginPwd"));
	  a.sendKeys("iH6B8i9z");	  
	  driver.findElement(By.className("login")).click();
	  String expectedTitle = "证券开户后台管理系统";
      String actualTitle = driver.getTitle();
      Assert.assertEquals(actualTitle, expectedTitle, "证券开户后台管理系统登陆成功");
    
      //显示等待,规定时间内等待某一元素可以找到,即中止等待
      new WebDriverWait(driver,3000).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id='menuList']/div[4]/div[1]/div[1]")));
      
      driver.findElement(By.xpath("//*[@id='menuList']/div[4]/div[1]/div[1]")).click();
      
      driver.findElement(By.id("datagrid-row-r4-2-3")).click();
      try {
		Thread.sleep(3000);
	} catch (InterruptedException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
      //new WebDriverWait(driver,10000).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id='menuList']/div[2]/div[1]/div[1]")));
      
       driver.findElement(By.xpath("//*[@id='menuList']/div[2]/div[1]/div[1]")).click();//证券开户
       
       driver.findElement(By.xpath("//*[@id='datagrid-row-r2-2-0']/td/div")).click();//渠道信息配置
       try {
		Thread.sleep(10000);//点击二级菜单加载页面数据时,须要设置一个等待时间,不然后续操做找不到操做对象即元素
	} catch (InterruptedException e2) {
		// TODO Auto-generated catch block
		e2.printStackTrace();
	}
       //driver.findElement(By.id("datagrid-row-r2-2-0")).click();
      // driver.findElement(By.xpath("//*[@id='btnSearchChannel']/span/span[1]")).click();
       //Outcaidan.getOutCaiDan(driver, "//*[@id='btnSearchChannel']/span/span[1]").click();
       //点击新增
       Outcaidan.createButton(driver, "Channel");
       try {
		Thread.sleep(2000);
	} catch (InterruptedException e2) {
		// TODO Auto-generated catch block
		e2.printStackTrace();
	}
       //判断新增对话框存在--/html/body/div[13]
      WebElement createswitch=driver.findElement(By.xpath("/html/body/div[13]"));
      if (createswitch !=null){
    	  System.out.println("点击新增按钮,能正常弹框");
      }else{
    	  System.out.println("点击新增按钮,无响应!");
      }
      String channelname="22";
      String aidvalue="06";
      String sidvalue="07";
      String ouidvalue="08";
      
      driver.findElement(By.xpath("//*[@id='channel_create']/div[2]/input")).sendKeys(channelname);
      driver.findElement(By.xpath("//*[@id='channel_create']/div[4]/input")).sendKeys(aidvalue);
      driver.findElement(By.xpath("//*[@id='channel_create']/div[5]/input")).sendKeys(sidvalue);
      driver.findElement(By.xpath("//*[@id='channel_create']/div[6]/input")).sendKeys(ouidvalue);
    
      //点击保存按钮-//*[@id="channle-create-buttons"]/a[1]/span/span[1]
      driver.findElement(By.xpath("//*[@id='channle-create-buttons']/a[1]/span/span[1]")).click();
      try {
		Thread.sleep(3000);
	} catch (InterruptedException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
     
     //List tablecontent =test2.getPageTableContent(driver, "//*[@id='product_mgt_wrap']/div/div[2]/div[2]");
      
    //*[@id="datagrid-row-r11-2-0"]--//*[@id="datagrid-row-r11-2-1"]-table每行的规律      
      driver.findElement(By.xpath("//*[@id='toolbar_channel']/ul/li[1]/div[1]/span/input[1]")).sendKeys("2");
       driver.findElement(By.xpath("//*[@id='btnSearchChannel']/span/span[1]")).click();
       try {
   		Thread.sleep(5000);
   	} catch (InterruptedException e1) {
   		// TODO Auto-generated catch block
   		e1.printStackTrace();
   	}
      if( test2.getPageTableContent(driver, "//*[@id='product_mgt_wrap']/div/div[2]/div[2]")!=null) {
    	  System.out.println("查询成功");
      }else{
    	  System.out.println("查询 失败");
      }
//      WebElement table= driver.findElement(By.xpath("//*[@id='product_mgt_wrap']/div/div[2]/div[2]/div[2]/div[1]/div/table"));
      WebElement table= driver.findElement(By.xpath("//*[@id='product_mgt_wrap']/div/div[2]/div[2]/div[2]/div[2]/table"));
      List<WebElement> rows = table.findElements(By.tagName("tr"));
      
		 int rowsnum=rows.size();
		 System.out.println("行数:"+rowsnum);
		 
		for(WebElement row:rows){
			List<WebElement> col = row.findElements(By.xpath("td"));			
			int colnum=col.size();
			 System.out.println("列数:"+colnum);
			
				
			 	List<String> cellcontent = new ArrayList<String>();
				/* for(WebElement cell:col){
						System.out.print(cell.getText() + "\t");
						cellcontent.add(cell.getText());	
						
					} */
									
				 for(int index =0; index <colnum;index++){
					 WebElement element = col.get(index);
					 String text = element.getText();
					 System.out.print("第"+index+"列的各字段值为 :"+text+"\t");
					 if(index == 2){
						 System.out.println();
						 if(channelname.equals(text)){
							 
							 System.out.println("新增成功,成功查询到channelname的值:"+text+"和"+channelname);						
							 
						 }else{
							 System.out.println("新增失败"+channelname);
							
						 }
					 }
				 }	 
				 System.out.println();
				 }	 		
		
			 /* for(int i=0;i<rowsnum;i++){
				//*[@id="product_mgt_wrap"]/div/div[2]/div[2]/div[2]/div[1]/div/table/tbody/tr-表头
				//*[@id="datagrid-row-r16-2-0"]--表行
				//*[@id="product_mgt_wrap"]/div/div[2]/div[2]/div[2]/div[1]/div/table/tbody/tr/td[1]
		    	  //if( table.findElement(By.xpath("//*[@id="datagrid-row-r16-2-i])) =
				//*[@id="datagrid-row-r16-2-0"]/td[3]/div
				  
		       }*/
		
      
       
     
      System.out.println();
      String getCurrentUrl = driver.getCurrentUrl();
      System.out.println("getCurrentUrl:"+getCurrentUrl);   
    
      String getTitle = driver.getTitle();
      System.out.println("getTitle:"+getTitle);
      
      String getWindowHandle = driver.getWindowHandle();
      System.out.println("getWindowHandle:"+getWindowHandle);
      

      try {
          Thread.sleep(10000);
      } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
      
      System.out.println("******结束测试");
		}
 
  
  @AfterClass
  public void tesrDown(){
      
      //driver.quit();
	  
	  
  }
  @BeforeMethod
  public void beforeMethod() {
  }

  @AfterClass
  public void afterClass() {
  }

}

 

以上是在系统中验证新增功能,新增一条记录后,通过查询,而后在表中遍历是否打到与预期一致的记录。sql

 

三、如下是一些封装的简单的方法,方便调用,代码以下:数据库

 

package seleniumtest;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class Outcaidan {
public static WebElement getOutCaiDan(WebDriver driver,String str){
	return driver.findElement(By.xpath(str));
}

//切换证券开户模块下的各个模块
	public static WebElement switchModuleZJ(WebDriver driver,String str){
		String elementStr = "//*[@id='datagrid-row-r3-2-" + str + "']/td/div";
		return driver.findElement(By.xpath(elementStr));
	}
//查询按钮
	public static void searchButton(WebDriver driver,String str){
		String elementStr = "//*[@id='btn" + str + "']/span";
		driver.findElement(By.xpath(elementStr)).click();
	}	
	
	//新增按钮
	public static void createButton(WebDriver driver,String str){
		String elementStr = "//*[@id='btnCreate" + str + "']/span/span[1]";
		driver.findElement(By.xpath(elementStr)).click();
	}
	//*[@id="btnCreateChannel"]/span/span[1]---//*[@id="btnCreatesystem"]/span/span[1]
	//删除按钮
	public static void deleteButton(WebDriver driver,String str){
		String elementStr = "//*[@id='btnDelete" + str + "']/span";
		driver.findElement(By.xpath(elementStr)).click();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//修改按钮
	public static void updateButton(WebDriver driver,String str){
		String elementStr = "//*[@id='btnUpdate" + str + "']/span";
		driver.findElement(By.xpath(elementStr)).click();
	}
	
	//获取文本输入框
	public static WebElement getInputText(WebDriver driver,String str){
		//String elementStr = "" + str + "";
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return driver.findElement(By.id(str));
	}
	
	
	
	public static void getRangeFromRows(WebDriver driver){
		WebElement table= driver.findElement(By.xpath("//*[@id='product_mgt_wrap']/div/div[2]/div[2]/div[2]/div[1]/div/table"));
		List<WebElement> rows = table.findElements(By.tagName("tr"));
		for(WebElement row:rows){
			List<WebElement> col = row.findElements(By.tagName("td"));
			for(WebElement cell:col){
				System.out.print(cell.getText() + "\t");
			}
			System.out.print("\n\t");
		}
	}

}
package seleniumtest;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class OperateDB{
	String url = "jdbc:oracle:thin:@(DESCRIPTION = (ADDRESS_LIST= (ADDRESS = (PROTOCOL = TCP)(HOST = 10.25.175.122)(PORT = 1524)))(CONNECT_DATA =(SERVICE_NAME = fatoas)))";
	String userName = "sioasdata";
	String userPW = "paic1234";
	String sql = null;
	Connection conn = null;
	Statement st = null;
	ResultSet rs = null;
	
	
	public Connection connectData(){
		//注册与加载链接数据库的驱动程序
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");	
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		//建立一个链接
		try {
			conn = DriverManager.getConnection(url, userName, userPW);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("数据库链接成功~!");
		return conn;
	}
	
	//获取数据结果集
	public void getDataResultSet(Connection conn,String sql){
		//获取数据表的列名
		ArrayList colName = new OperateDB().getTableColumnName(conn, sql);
		
		try {
			st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		try {
			rs = st.executeQuery(sql);
			while(rs.next()){
				for(int i=0;i<colName.size();i++){
					System.out.print(rs.getString((String)colName.get(i)) + " | ");
				}
				System.out.println();
			}
			
			rs.close();
			st.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	//获取数据表的列名
	public ArrayList getTableColumnName(Connection conn,String sql){
		ArrayList<String> colName = new ArrayList<>();
		
		try {
			st = conn.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			rs = st.executeQuery(sql);
			ResultSetMetaData rsm = rs.getMetaData();
			for(int i=1;i<rsm.getColumnCount();i++){
				colName.add(rsm.getColumnLabel(i));
			}
			
			rs.close();
			st.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
			
		return colName;
	}
	
	//关闭数据库
	public void closeConection(Connection conn){
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

 

package seleniumtest;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;


public class test2 {

	//赋予窗口焦点
		public static void getWindowFocus(WebDriver driver,String str){
			//当前窗口获取焦点
			Common.setFocus(driver);
			//点击“证券开户”标签
			//driver.findElement(By.xpath("//div[@id='menuSys']/div/div[2]")).click();
			driver.findElement(By.xpath(str)).click();
		}
	
	//赋予元素焦点
			public static void setFocus(WebDriver driver){
		/*		Actions action = null;
				WebElement button = null;
				*/
				
		/*		FirefoxProfile file = new FirefoxProfile();
				DesiredCapabilities ds = DesiredCapabilities.firefox();
				ds.setCapability(FirefoxDriver.PROFILE, file);
				driver = new FirefoxDriver(ds);
				action = new Actions(driver);
				driver.get("http://www.baidu.com");
				driver.manage().window().maximize();
				//查找你须要设置焦点的元素
				button = driver.findElement(By.xpath("//div[@id='menuSys']/div/div[2]"));
				action = new Actions(driver);
				*/
				//窗体最大化,把焦点定位至当前窗口
				driver.manage().window().maximize();
				 

				//鼠标左键单击
				//action.click(button).perform();
		/*		
				//对该元素进行右击操做
				action.contextClick(button).perform();
				//按ESC键返回,设置焦点成功
				try {
					new Robot().keyPress(KeyEvent.VK_ESCAPE);
				} catch (AWTException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				*/
			}
			
			//获取表头名(页数大于1的时候须要用来添加json中)
			public static List getTableTitleName(WebDriver driver){
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				WebElement title = driver.findElement(By.xpath("//*[@id='product_mgt_wrap']/div[1]/div[2]/div[2]/div[2]/div[1]/div/table/tbody/tr"));		                                              	
				List<WebElement> cols = title.findElements(By.tagName("td"));
				List<String> colNames = new ArrayList<>();
				for(WebElement cell:cols){
					//String str = cell.getText();
					colNames.add(cell.getText());
					}
				return colNames;
			}
			
			//获取当前页面的table内容
			static int count = 0;
			public static List getPageTableContent(WebDriver driver,String refreshElement){
			//public static List getPageTableContent(WebDriver driver,WebElement table,String refreshElement){
				
				//获取当前页面的table
				WebElement  table = driver.findElement(By.xpath(refreshElement));
				//table = driver.findElement(By.xpath("//*[@id='product_mgt_wrap']/div[1]/div[2]/div[2]/div[2]/div[2]/table"));
				
				List<WebElement> rows = table.findElements(By.tagName("tr"));//根据行标签,获取全部行对象
				//String[] tableTitle = {"编号","配置名称","首页返回按钮","首页banner显示","极简尾页",""};
				ArrayList<String> tableContent = new ArrayList<>();
				for(WebElement row:rows){//从全部行中遍历每一行
					List<WebElement> col = row.findElements(By.tagName("td"));//一行中,全部列标签,
					for(WebElement cell:col){//一行中,全部的列(也就是单元格)
						String content = cell.getText();//每一个单元格的内容
						tableContent.add(content);
						//System.out.println(content + "...content");
						
					}
				}
				return tableContent;
			}
			
			//获取总页数
			public static int getPageAllNo(WebDriver driver){
				//获取总页数
						String pageCountSumStr = driver.findElement(
								By.xpath("//*[@id='product_mgt_wrap']/div/div[2]/div[3]/table/tbody/tr/td[8]/span")).getText();
						int pageCountSum = Integer.parseInt(pageCountSumStr.substring(3));
						return pageCountSum;
			}
			
			//获取当前页数
			public static int getCurrentPageNo(WebDriver driver){
				//总页数的元素定位
				String pageCountSumStr = driver.findElement(
						By.xpath("//*[@id='product_mgt_wrap']/div/div[2]/div[3]/table/tbody/tr/td[8]/span")).getText();
				//获取当前页面页数
						String pageSource = driver.getPageSource();//获取当前页的源文件
						
						String pageElement = "pagination-num\" type=\"text\" value=\"";//在源文件中查找含有该字段的位置
						int pageIndex = pageSource.indexOf(pageElement);//经过上面的字段位置,定位文本框中的当前页数
						//经过定位出来的位置,获取文本框中的值
						int currentPageCount = Integer.parseInt(pageSource.substring(pageIndex+pageElement.length(), pageIndex+pageElement.length()+pageCountSumStr.substring(3).length()));
						return currentPageCount;
			}
			//根据表格单元个内容定位单元格所在行
			/**
			 * @author:苏宝伢 email:by.su@qq.com
			 * 1.进来先获取页面的总页数
			 * 2.若是总页数大于1
			 * 3.把每一条记录全部字段和记录所在的当前页数存入json中,表头为Key,值为Value。
			 * #3.把每一条记录中除编号外的其余字段和记录所在的当前页数存入json中,编号做为Key,其余已经存入json做为Value存入HashMap中。
			 * 4.传入须要定位的字符串,根据字符在json中查找对应的页数,把全部含有该字符的记录存到
			 *** --暂时未按以上逻辑实现,后续优化的时候实现
			 * @throws InterruptedException 
			 */
			public static void getRangeFromRows(WebDriver driver,String str) throws InterruptedException{
				
				Thread.sleep(800);
				//str为定位的关键字
				int pageCountSum = getPageAllNo(driver);//获取总页数
				int currentPageCount = getCurrentPageNo(driver);//获取当前页数
				
				//须要定位元素的xpath
				String strContent = "//*[contains(text(),'" + str + "')]";
				//当前页面的table的元素定位
				String refreshElement ="//*[@id='product_mgt_wrap']/div[1]/div[2]/div[2]/div[2]/div[2]/table";
				//获取当前页面的table
				WebElement table= driver.findElement(By.xpath(refreshElement));
				                                              
				if(pageCountSum == 1){
					ArrayList<String> tableContent = (ArrayList)getPageTableContent(driver,refreshElement);
					for(String content:tableContent){
						if(content.contains(str)){//若包含须要查找定位的关键字str
							driver.findElement(By.xpath(strContent)).click();
						}
					}
				}else{//页面总数大于1的时候
					boolean flag = false;//设置一个跳出的标志位
					for(int i=0;i<pageCountSum&&!flag;i++){
						//当前页面等于1的时候
						if(currentPageCount==1){
							ArrayList<String> tableContent = (ArrayList)getPageTableContent(driver,refreshElement);
							
							for(String content:tableContent){
								if(content.contains(str)){//若包含须要查找定位的关键字str
									driver.findElement(By.xpath(strContent)).click();
									flag = true;//若找到,即跳转出循环
									break;//退出该循环体
								}
							}
							Thread.sleep(1000);
							currentPageCount += 1;//设置页数为2,页数大于1,逻辑转到else下面的代码块
						}else{
							//点击下一页的按钮,页面跳转到下一页,从第1页跳转到第2页
							driver.findElement(By.xpath("//*[@id='product_mgt_wrap']/div/div[2]/div[3]/table/tbody/tr/td[10]/a/span/span[2]")).click();
							Thread.sleep(800);
							//从第2页开始,每翻一页,都进行查找定位
							for(int n=2;n<=pageCountSum&&!flag;n++){
								ArrayList<String> tableContent = (ArrayList)getPageTableContent(driver,refreshElement);
								//点击下一页按钮
								driver.findElement(By.xpath("//*[@id='product_mgt_wrap']/div/div[2]/div[3]/table/tbody/tr/td[10]/a/span/span[2]")).click();
								Thread.sleep(800);
								currentPageCount = getCurrentPageNo(driver);//获取跳转后的页数
								
								for(String content:tableContent){
									if(content.contains(str)){//若包含须要查找定位的关键字str
										driver.findElement(By.xpath(strContent)).click();
										flag = true;//找到定位跳转到flag标志位
									}
								}
								/*//获取全部页面的内容
								tableContentAll.addAll((ArrayList)getPageTableContent(driver,table));*/
							}
						}
					}
					Thread.sleep(1000);
				}
			}
			
			

}
相关文章
相关标签/搜索