Selenium之偷懒教程

进来一直停留在基础理论知识的学习中,认为太乏味,就写了一个网页自己主动化的demo:自己主动写日报。省的以后自己打开网页写啦。

直接上代码:


自己主动填写日报DEMO


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import junit.framework.TestCase;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Select;

public class AutoLog extends TestCase {
	private static final String URL = "your log website";
	private static int mHours = 8;
	private static final String CONTENT_FILE = System.getProperty("user.dir")
			+ File.separator + "config" + File.separator + "logcontent.txt";
	private static final String DRIVER_FILE = System.getProperty("user.dir")
			+ File.separator + "driver" + File.separator + "IEDriverServer.exe";
	private static String mContext = "Job :";
	private static String mDate = "1900-1-1";
	private WebDriver mDriver = null;
	private String mFlag = "FAIL";

	@Override
	public void setUp() throws Exception {
		calculateHours();
		config();
	}

	@Test
	public void test_WriteLog() {
		try {
			System.setProperty("webdriver.ie.driver", DRIVER_FILE);
			mDriver = new InternetExplorerDriver();
			mDriver.get(URL);

			Select select = new Select(mDriver.findElement(By
					.id("task_ProductName")));
			select.selectByVisibleText("iTest");
			Select select1 = new Select(mDriver.findElement(By
					.id("field_Class_1")));
			select1.selectByVisibleText("Test_Development");
			Select select2 = new Select(mDriver.findElement(By
					.id("field_Class_2")));
			select2.selectByVisibleText("Coding");
			WebElement text = mDriver.findElement(By.id("field_CostTime"));
			text.sendKeys(mHours + "");
			mDriver.switchTo().frame("contentFrame");
			mDriver.switchTo().frame(0);
			WebElement content = mDriver
					.findElement(By.className("ke-content"));
			content.click();
			content.sendKeys(mContext);

			mDriver.switchTo().defaultContent();
			WebElement submit = mDriver.findElement(By.name("submit2"));
			// submit.click();

			// WebElement table =
			// mDriver.findElements(By.id("SubmitForm")).get(1)
			// .findElement(By.id("myTodoTable"));
			WebElement table = mDriver.findElement(By.id("this_last"))
					.findElement(By.tagName("table"));
			WebElement tr = table.findElement(By.tagName("tbody")).findElement(
					By.tagName("tr"));
			if (mDate
					.equals(tr.findElements(By.tagName("td")).get(1).getText())) {
				mFlag = "SUCCESS[" + tr.getText() + "]";
			}

		} catch (Exception e) {
			e.printStackTrace();
			mFlag = "EXCEPTION";
		} finally {
			sendMail(mFlag);

		}
	}

	public void tearDown() throws Exception {
		mDriver.quit();
	}

	public void calculateHours() {
		Date date = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		mDate = df.format(date);
		Calendar c = Calendar.getInstance();
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		mHours = hour - 9 - 1;
		minute = minute < 30 ? 0 : 1;
		mHours += minute;
		mHours = mHours < 8 ?

8 : mHours; } public void config() { StringBuilder sb = new StringBuilder(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream( CONTENT_FILE), "UTF-8")); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { mContext += sb; try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void sendMail(String result) { MailSender javaEmail = new MailSender(); javaEmail.setMailServerProperties(); try { javaEmail.createEmailMessage(result); javaEmail.sendEmail(); } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }



以下说一下流程。


1.新建java项目


导入selenium-server-standalone-2.42.2.jarmailapi.jarsmtp.jar和Junit库。第一个jar包为selenium-webdriver依赖jar包,后两个为发送邮件用的。


2.下载IEDriverServer


由于我用的是IE。所以我须要在代码里配置IE的驱动程序。

前提是要下到本地。分32位的和64位,我刚開始由于下错64位的,老是启动不了浏览器,折腾了非常长时间。所以看好机器再下载。我这里上传了32位的IEDriverServer


3.代码编写


首先启动浏览器:第一步要把你的IEDriverServer的文件夹设置到环境变量中,然后启动浏览器,输入网址。


System.setProperty("webdriver.ie.driver", DRIVER_FILE);
			mDriver = new InternetExplorerDriver();
			mDriver.get(URL);


等待网页载入完成以后就是以下 的样子:



然后就是定位我所要选择和填写的控件:首先3个选择框,通过selenium的select对象定位并选择我要的,


Select select = new Select(mDriver.findElement(By.id("task_ProductName")));
select.selectByVisibleText("iTest");
Select select1 = new Select(mDriver.findElement(By.id("field_Class_1")));
select1.selectByVisibleText("Test_Development");
Select select2 = new Select(mDriver.findElement(By.id("field_Class_2")));
select2.selectByVisibleText("Coding");


查看页面控件元素的方式是,在当前页面上按F12.





然后按一下工具中的光标button,点击你想看的控件。



所以上面三个选择框都是通过id来定位的。


以下来定位时间输入框:


WebElement text = mDriver.findElement(By.id("field_CostTime"));
text.sendKeys(mHours + "");

这个非常easy。以id来定位。时间的计算我是通过实时来计算的。以9点上班为准。计算当前时间与9点的差值。

每一个公司的规章制度不一,每一个公司计算方式也不一样的。



然后就填写日报内容,我用的方式是把日报的内容写在一个txt文档中,然后读这个文档写。



可是定位日报输入框有点麻烦。由于它是存在于iframe中的。直接定位不到。





所以先得转换到iframe中,contentFrame中又包括了一个iframe。然后还得转。这个时候才真正的转到了class名为ke-edit-iframe中。

然后才干定位输入框。


mDriver.switchTo().frame("contentFrame");
mDriver.switchTo().frame(0);
WebElement content = mDriver.findElement(By.className("ke-content"));
content.click();
content.sendKeys(mContext);


填完上面的内容以后就要提交啦。可是提交button却不在刚才的iframe中。



所以还得先转换到当前上下文。然后再定位提交button。


mDriver.switchTo().defaultContent();
WebElement submit = mDriver.findElement(By.name("submit2"));
submit.click();


好,到这一步就算完毕了。

可是做为一个case。自然要有checkpoint。所以我在代码的后面加了一个推断,推断我是否成功填写日报,然后将结果发送到我的邮箱中。


WebElement table = mDriver.findElement(By.id("this_last"))
					.findElement(By.tagName("table"));
			WebElement tr = table.findElement(By.tagName("tbody")).findElement(
					By.tagName("tr"));
			if (mDate
					.equals(tr.findElements(By.tagName("td")).get(1).getText())) {
				mFlag = "SUCCESS[" + tr.getText() + "]";
			}

sendMail(mFlag);



原文地址:https://www.cnblogs.com/lcchuguo/p/5184249.html