最近做了一個selenium+java實例僅供參考,涉及的知識有:IE的啓動及安全設置,alert提示框、Frame,上傳文件的處理方式。
package com.safeFile;
import static org.junit.Assert.fail;
import java.io.File;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class index {
private WebDriver driver;
private String baseUrl; //登錄地址
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String mainHandle; //主窗口ID
Set<String> allWindowHandle ; //創建set集合,即所有窗口的句柄數組
//----------------公文傳輸,輸入參數----------
String publicTitle;//公文標題
String subject;//主題詞
String sendDepartment;//發文單位
String sendUser;//發文人
//正文文檔暫無,同附件一樣處理
//附件上傳--用autoIT打exe包
String Remarks;//備註
@Before
public void setUp() throws Exception {
//啓動IE瀏覽器
File file = new File("C:\\Program Files (x86)\\Internet Explorer\\IEDriverServer.exe");//配置本地IEDriverServer.exe的存放路徑,此文件需要從網上下載。
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());//配置本地IEDriverServer.exe的存放路徑
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer(); //導入capabilities包,聲明一個capabilities對象
capabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);//瀏覽器啓動前清理髒數據
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);//忽略IE安全設置,也可以設置IE的安全模式全部打開或全部關閉
capabilities.setCapability("ignoreProtectedModeSettings",true);//忽略IE安全模式
driver = new InternetExplorerDriver(capabilities);
driver.manage().window().maximize();//最大化瀏覽器
//------啓動火狐-------
// driver = new FirefoxDriver();
baseUrl = "http://192.168.0.51:9001/login1.aspx";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
//-------------------切換窗口-----------------
public void getNewHandle(String mainHandle,Set<String> allWindowHandle) {
// set = driver.getWindowHandles(); //創建set集合,即句柄數組
Iterator<String> handles=allWindowHandle.iterator(); ///迭代器取得所有set集合內容
System.out.println("set.length:"+allWindowHandle.size());
while (handles.hasNext()) { //是否還存在句柄
String sonHandle = handles.next(); //循環取得各個元素值
if (!sonHandle.equals(mainHandle)) //“登錄後的取得的所有句柄”與“登錄之前取得的句柄”進行對比,如果不同則執行窗口跳轉
{
driver.switchTo().window(sonHandle);
}
}
}
//----------------alert提示處理----------------------
public void acceptAlert() throws Exception
{
boolean isExist = false;
Alert alert = null;
for (int i = 0; i < i + 1; i++)
{
if (!isExist)
{
try
{
alert = driver.switchTo().alert();
isExist = true;
break;
}
catch (NoAlertPresentException e)
{
isExist = false;
}
}
}
alert.accept();
}
@Test
public void testSafeFile() throws Exception {
driver.get(baseUrl); //打開網址
mainHandle=driver.getWindowHandle(); //取得登錄前的窗口句柄
Thread.sleep(2000);
try{ //用戶登錄
driver.findElement(By.id("txtUserName")).clear();
driver.findElement(By.id("txtUserName")).sendKeys("admin");
System.out.println("2");
driver.findElement(By.id("txtPassword")).clear();
driver.findElement(By.id("txtPassword")).sendKeys("1111");
Thread.sleep(1000);
driver.findElement(By.id("btnLogin")).click();
Thread.sleep(2000);
}catch(Exception e){
System.out.println("alert('登錄失敗!')");
}
try{ //-----------新建發文--------
driver.findElement(By.xpath("//tbody/tr/td[1]/div/ul/ul[2]/ul/li[1]/span")).click(); //打開公文管理
Thread.sleep(1000);
System.out.println("待發公文》新建");
driver.findElement(By.xpath("//tbody/tr/td[1]/div/ul/ul[2]/ul/li[2]/ul/li[1]/a")).click(); //打開待發公文
driver.switchTo().frame("mianframe"); //返加父driver.SwitchTo().DefaultContent();
driver.findElement(By.id("txtDocTitle")).sendKeys("testcase");//標題輸入
System.out.println("3");
WebElement element= driver.findElement(By.cssSelector("a[onclick*='SelectMainDep']"));
element.click();
System.out.println("4");
Thread.sleep(2000);
allWindowHandle = driver.getWindowHandles();
getNewHandle(mainHandle,allWindowHandle);
driver.findElement(By.id("treeDept_3_switch")).click(); //打開二級單位目錄
driver.findElement(By.id("treeDept_31_switch")).click(); //打開三級單位目錄
for(int i=38;i<=40;i++){
driver.findElement(By.id("treeDept_"+i+"_check")).click(); //選擇單位
}
driver.findElement(By.id("btnOK")).click(); //確定
Thread.sleep(1000);
mainHandle=driver.getWindowHandle(); //登錄後取得窗口句柄
Set<String> set2 = driver.getWindowHandles(); //創建set集合,即句柄數組
Iterator<String> handles2 = set2.iterator(); //迭代器取得所有set集合內容
System.out.println("返回主頁");
System.out.println("set2.length:"+set2.size());
while (handles2.hasNext()) { //是否還存在句柄
String sonHandle = handles2.next(); //循環取得各個元素值
System.out.println("main:"+mainHandle);
System.out.println("son:"+sonHandle);
if (!sonHandle.equals(mainHandle)) //“登錄後的取得的所有句柄”與“登錄之前取得的句柄”進行對比,如果不同則執行窗口跳轉
{
driver.switchTo().window(sonHandle);
}
}
driver.switchTo().frame("mianframe"); //進入frame
driver.findElement(By.id("Button2")).click();
Thread.sleep(1000);
Runtime rn = Runtime.getRuntime();
Process p = null;
try {
p = rn.exec("E:/openUpfile.exe");
System.out.println("p="+p);
Thread.sleep(2000);
} catch (Exception e) {
System.out.println("Error upfile!");
}
Thread.sleep(2000);
allWindowHandle = driver.getWindowHandles();
getNewHandle(mainHandle,allWindowHandle);
driver.switchTo().frame("mianframe"); //進入frame
System.out.println("save="+driver.findElement(By.id("btnSave")));
driver.findElement(By.id("btnSave")).click();
Thread.sleep(5000);
acceptAlert();//點擊確定;
System.out.println("發文成功");
}catch(Exception e){
System.out.println("發文失敗");
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
--------------------------------------autoIT處理上傳文件代碼-----------------
;ControlFocus("title","text",controlID) Edit1=Edit instance 1
ControlFocus("選擇要加載的文件", "","Edit1") ;定位彈窗
; Wait 10 seconds for the Upload window to appear
WinWait("[CLASS:#32770]","",10)
; Set the File name text on the Edit field
ControlSetText("選擇要加載的文件", "", "Edit1", "D:\2000Project.et")
Sleep(2000)
; Click on the Open button
ControlClick("選擇要加載的文件", "","Button1");