用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);
				}
			}
			
			

}
相關文章
相關標籤/搜索