Selenium之偷懶教程

來源:互聯網
上載者:User

進來一直停留在基礎理論知識的學習中,覺得太乏味,就寫了一個網頁自動化的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";@Overridepublic void setUp() throws Exception {calculateHours();config();}@Testpublic 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 blocke.printStackTrace();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {mContext += sb;try {br.close();} catch (IOException e) {// TODO Auto-generated catch blocke.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 blocke.printStackTrace();} catch (MessagingException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


下面說一下流程。


1.建立java項目


匯入selenium-server-standalone-2.42.2.jar、mailapi.jar、smtp.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.





然後按一下工具中的游標按鈕,點擊你想看的控制項。



所以上面三個選擇框都是通過id來定位的。


下面來定位時間輸入框:


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

這個很容易,以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);


填完上面的內容以後就要提交啦。但是提交按鈕卻不在剛才的iframe中。



所以還得先轉換到當前上下文,然後再定位提交按鈕。


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



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.