最近做了一个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");