1、WebDriver处理一些弹窗
import java.util.Set;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class AlertOperate {
static WebDriver dr = new InternetExplorerDriver();
public static void main(String args[]) throws InterruptedException{
dr.get("www.baidu.com");
dr.findElement(By.id("lb")).click();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tanchukuang();
}
//处理潜在的1个alert(javascript弹出框)
public boolean dealPotentialAlert(WebDriver driver,boolean option) {
boolean flag = false;
try {
Alert alert = driver.switchTo().alert();
if (null == alert)
throw new NoAlertPresentException();
try {
if (option) {
alert.accept();
System.out.println("Accept the alert: " + alert.getText());
} else {
alert.dismiss();
System.out.println("Dismiss the alert: " + alert.getText());
}
flag = true;
} catch (WebDriverException ex) {
if (ex.getMessage().startsWith("Could not find"))
System.out.println("There is no alert appear!");
else
throw ex;
}
} catch (NoAlertPresentException e) {
System.out.println("There is no alert appear!");
}
return flag;
}
//处理非JS弹窗
public static boolean testNewWindow(){
//当前窗口句柄
String currentHandle = dr.getWindowHandle();
//得到所有窗口的句柄
Set<String> handles = dr.getWindowHandles();
handles.remove(currentHandle);
if (handles.size() > 0) {
try{
dr.switchTo().window(handles.iterator().next());
//dr.switchTo().window(dr.getWindowHandles().iterator().next());
return true;
}catch(Exception e){
System.out.println(e.getMessage());
return false;
}
}
System.out.println("Did not find window");
return false;
}
//一般弹出窗口
public static void tanchukuang() throws InterruptedException{
//得到所有窗口
Set<String> allWindowsId = dr.getWindowHandles();
//通过查找页面内容得到新的窗口
for(String windowId : allWindowsId){
dr.switchTo().window(windowId);
Thread.sleep(1000);
dr.findElement(By.id("TANGRAM__PSP_10__userName")).sendKeys("test");
//第一个按钮是确定按钮
//dr.findElement(By.xpath("//button[@type='button']")).click();
//System.out.println(dr.switchTo().window(windowId).getTitle());
break;
}
}
}
2、一些数据类型转换
public class Chanage {
//int to String
public static String IntToString(int i){
String s = Integer.toString(i);
return s;
}
//String to int
public static int StringToInt(String s){
int i = Integer.parseInt(s);
return i;
}
}
3、和数据库交互
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.Connection;
class ConnMySQL {
Connection conn;
Statement stmt;
ResultSet rs1;
int rs2;
public void connection() throws Exception{
String db = "meeting";
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://172.16.3.9:3306/"+db;
String uname = "admin";
String pwd = "itserver";
//加载驱动
Class.forName(driver);
//连接数据库
conn = (Connection) DriverManager.getConnection(url, uname, pwd);
if(!conn.isClosed()){
//System.out.println("连接成功!");
}
}
//执行查询操作返回ResultSet类型
public void executeSql0(String sql) throws SQLException{
//创建语句对象,用来执行sql语句
stmt = conn.createStatement();
//执行sql
rs1 = stmt.executeQuery(sql);
while(rs1.next()){
String name = rs1.getString("meetingId");
String subject = rs1.getString("e164");
String regionName = rs1.getString("state");
System.out.println(name+" "+subject+" "+regionName);
}
rs1.close();
}
//执行查询操作返回ResultSet类型
public void executeSql1(String sql) throws SQLException{
//创建语句对象,用来执行sql语句
stmt = conn.createStatement();
//执行sql
rs1 = stmt.executeQuery(sql);
while(rs1.next()){
String id = rs1.getString("id");
String subject = rs1.getString("subject");
String startTime = rs1.getString("startTime");
String endTime = rs1.getString("endTime");
String organiger = rs1.getString("organiger");
String status = rs1.getString("status");
System.out.println(id+" "+subject+" "+startTime+" "+endTime+" "+organiger+" "+status);
}
rs1.close();
conn.close();
}
//执行增删改操作返回int类型
public void executeSql2(String sql) throws SQLException{
stmt = conn.createStatement();
rs2 = stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
}
4、创建EXCEL
// 生成Excel的类
import java.io.File;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class CreateExcel{
public static void main(String args[]){
//Create_Excel c_e = new Create_Excel();
//c_e.createexcel();
//System.out.printf("success!!");
}
}
class Create_Excel{
public void createexcel(){
try{
// 打开文件
WritableWorkbook book = Workbook.createWorkbook(new File("test.xls"));
// 生成名为“第一页”的工作表,参数0表示这是第一页
WritableSheet sheet = book.createSheet("第一页",0);
// 在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
// 以及单元格内容为test
Label label1 = new Label(0,0,"test");
Label label2 = new Label(1,1,"test");
// 将定义好的单元格添加到工作表中
sheet.addCell(label1);
sheet.addCell(label2);
/*
* 生成一个保存数字的单元格 必须使用Number的完整包路径,否则有语法歧义 单元格位置是第二列,第一行,值为555
*/
jxl.write.Number number = new jxl.write.Number(1,0,555);
sheet.addCell(number);
// 写入数据并关闭文件
book.write();
book.close();
}catch(Exception e){
System.out.println(e);
}
}
}
5、读取EXCEL
// 读取Excel的类
import java.io.File;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
/*
* 参数1:第几个工作表
* 参数2:第几列
* 参数3:第几行
* 参数都从0开始
* 返回值:当前单元格的数据
*/
public class ReadExcel{
static String result;
static Workbook book;
static Sheet sheet;
public static void main(String args[]){
//readExcel(0,1,0);
excelNum(0);
}
public static String readExcel(int no,int row,int line){
try{
book = Workbook.getWorkbook(new File("test.xls"));
// 获得第一个工作表对象
sheet = book.getSheet(no);
// 得到第一列第一行的单元格
Cell cell1 = sheet.getCell(row,line);
result = cell1.getContents();
System.out.println(result);
book.close();
}catch(Exception e){
System.out.println(e);
}
return result;
}
//返回行数
public static int excelNum(int no){
int col = 0;
int row = 0;
try{
book = Workbook.getWorkbook(new File("test.xls"));
sheet = book.getSheet(no);
//得到行数和列数
col = sheet.getColumns(); //列数
row = sheet.getRows(); //行数
System.out.println(col+" 列");
System.out.println(row+" 行");
book.close();
}catch(Exception e){
System.out.println(e);
}
return row;
}
}
6、更新EXCEL
import java.io.File;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class UpdateExcel{
public static void main(String args[]){
try{
// Excel获得文件
Workbook wb = Workbook.getWorkbook(new File("test.xls"));
// 打开一个文件的副本,并且指定数据写回到原文件
WritableWorkbook book = Workbook.createWorkbook(new File("test.xls"),wb);
// 添加一个工作表
WritableSheet sheet = book.createSheet("第二页",1);
sheet.addCell(new Label(0,0,"第二页的测试数据"));
book.write();
book.close();
}catch(Exception e){
System.out.println(e);
}
}
}
7、WebDriver判断元素是否存在
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
/*
* 判断一个元素是否存在
*/
public class ElementIsExsit {
//查找一个元素是否存在
public boolean isElementExsit(WebDriver driver, By locator) {
boolean flag = false;
try {
WebElement element=driver.findElement(locator);
//flag = true;
flag=null!=element;
System.out.println("元素: " + locator.toString()+ " 存在!");
}catch(NoSuchElementException e) {
System.out.println("元素: " + locator.toString()+ " 不存在!");
flag = false;
}
return flag;
}
//如何使用上面的方法
public void test(){
WebDriver driver = new InternetExplorerDriver();
//显性等待
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
By locator = By.id("id");
isElementExsit(driver,locator);
}
}
8、java下载图片
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
public class Movision_verifyImage {
private static HttpClient hc = new DefaultHttpClient();
public static void main(String args[]) throws ClientProtocolException, IOException, ParseException, URISyntaxException{
//获取图片验证码页面随机参数(当前时间)
long date = new Date().getTime();
System.out.println(date);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("random",Long.toString(date)));
get("http://172.16.3.6/admin/portalVerifyImage",params);
}
/*
* 带参数的GET请求
*
*/
public static void get(String url,List<NameValuePair> params) throws ParseException, UnsupportedEncodingException, IOException, URISyntaxException{
//get请求
HttpGet httpget = new HttpGet(url);
//设置参数
String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
httpget.setURI(new URI(httpget.getURI().toString()+"?"+str));
//发送请求
HttpResponse re = hc.execute(httpget);
//获取相应实体
HttpEntity entity = re.getEntity();
if (entity != null && entity.isStreaming()) {
File storeFile = new File("F:\\test.jpg");
FileOutputStream fos = new FileOutputStream(storeFile);
// 将取得的文件文件流写入目标文件
InputStream is = entity.getContent();
byte[] b = new byte[1024];
int j = 0;
while ((j = is.read(b)) != -1) {
fos.write(b, 0, j);
}
fos.flush();
fos.close();
} else {
System.out.println("[" + url + "] 未找到.");
return;
}
//关闭连接
hc.getConnectionManager().shutdown();
}
}
9、java远程登录linux并执行命令
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
/*
* 远程调用linux下的vmstat命令,并将结果完整写入文件中
*/
public class SSHTest {
/**
* @param args
* @throws IOException
*/
/*
* 主机地址、端口、用户名、密码
*/
static String hostName = "172.16.3.9";
static int port = 2222;
static String userName = "root";
static String pwd = "kedats";
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
System.out.println("开始连接主机");
Connection conn = new Connection(hostName, port);
conn.connect();
boolean isdenglu = conn.authenticateWithPassword(userName, pwd);
if (isdenglu) {
System.out.println("ssh2登陆成功");
} else {
System.out.println("登陆失败");
}
//System.out.println("当前目录:");
Session ses = conn.openSession();
ses.execCommand("vmstat 2");
InputStream stdout = new StreamGobbler(ses.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
FileWriter fw = new FileWriter("F:\\vmstat.txt");
while (true)
{
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
fw.write(line+"\r\n",0,line.length()+2);
fw.flush();
// OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("data2.txt"));
// osw.write(line,0,line.length());
// osw.flush();
// PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("hello3.txt")),true);
// pw.println(line);
}
System.out.println("运行结果:"+ses.getExitStatus());
//关闭文件
fw.close();
ses.close();
conn.close();
}
}
10、java将控制台打印写入日志文件
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class ToLog {
static GregorianCalendar time = new GregorianCalendar();
// int year = time.get(Calendar.YEAR); //得到日期的年份
// int day = time.get(Calendar.DAY_OF_MONTH); //得到日期的天
// int month = time.get(Calendar.MONTH)+1; //得到日期的月份
// int weekDay = time.get(Calendar.DAY_OF_WEEK); //得到日期为星期几
// int weekOfYear = time.get(Calendar.WEEK_OF_YEAR); //得到日期为年的第几周
// int weekOfMonth = time.get(Calendar.WEEK_OF_MONTH); //得到日期为月的第几周
private static final String getToday = time.get(Calendar.YEAR)+"-"+(time.get(Calendar.MONTH)+1)+"-"+time.get(Calendar.DAY_OF_MONTH)+"-";
private static final String filePath = "C:\\Documents and Settings\\Administrator\\workspace\\Movision_script\\logs\\"+getToday+"log.html";
//写入文件
public void toLog(String message){
StackTraceElement stack[] = (new Throwable()).getStackTrace();
StackTraceElement s = stack[1];
String headerMessage = s.getClassName()+"."+s.getMethodName()+"()"+"★LineNum:"+s.getLineNumber()+"<br />★Message: ";
headerMessage = addDateTimeHeader(headerMessage);
message = headerMessage + message + "<br />========================================================================================================================<br /><br />";
FileWriter fw = null;
File file = null;
try{
file = new File(filePath);
fw = new FileWriter(file,true);
fw.write(message);
}catch(IOException ie){
ie.printStackTrace();
}finally{
try{
fw.close();
}catch(IOException ie){
ie.printStackTrace();
}
}
}
@SuppressWarnings("deprecation")
public String addDateTimeHeader(String headerMessage) {
String dateTimeHeader = new Date().toLocaleString()+"★";
return dateTimeHeader += headerMessage;
}
// public static void main(String args[]){
// ToLog log = new ToLog();
// String message = "这只是测试";
// log.toLog(message);
// }
}
写分享这么多吧~各位,晚安!