1、切換css
1.window窗口切換html
@Test public void test3(){ System.out.println(driver.getWindowHandle()); String oldHandle = driver.getWindowHandle(); //使用javaScript打開一個新標籤頁 JavascriptExecutor oJavaScriptExecute =(JavascriptExecutor)driver; oJavaScriptExecute.executeScript("window.open();"); System.out.println("there are "+driver.getWindowHandles().size()+"windows"); for(String handle:driver.getWindowHandles()){ System.out.println(handle); if (! handle.equals(oldHandle)){ //新標籤頁打開http://www.testerhome.com driver.switchTo().window(handle); driver.get("http://www.testerhome.com"); break; } } driver.close(); //切換回第一個的標籤頁,不然handle依然停留在已關閉的標籤頁。針對不存在的標籤操做,會報NoSuchWindowException的異常。如圖2 driver.switchTo().window(oldHandle); }
結果:
不切換回原有標籤頁
2.切換到對話框java
對話框的辨別https://blog.csdn.net/huilan_same/article/details/52298460git
alert爲瀏覽器彈出框,通常是用來確認某些操做、輸入簡單的text或用戶名、密碼等,根據瀏覽器的不一樣,彈出框的樣式也不同。這種彈窗是沒法取到元素的,即alert是不屬於網頁DOM樹的。如從左到右,依次爲alert\confirm\promptgithub
div假裝對話框,是經過網頁元素假裝成對話框,這種對話框內容較多,不會隨瀏覽器而改變,在網頁中能獲取到元素。以下圖web
driver.switchTo().alert().accept(); //等同於點擊確認或OK
driver.switchTo().alert().dismiss(); //等同於點擊取消或cancel
driver.switchTo().alert().getText(); //對有信息顯示的alert框,獲取alert文本內容
driver.switchTo().alert().sendKeys("Hello world"); //對有提交需求的文本框發送文本
示例1:switch_to.alert accept textchrome
測試連接: http://sahitest.com/demo/alertTest.htmapache
@Test public void test4() throws InterruptedException{ driver.get("http://sahitest.com/demo/alertTest.htm"); driver.findElement(By.xpath("//input[@name='b1']")).click(); Thread.sleep(2000); driver.switchTo().alert().accept(); Thread.sleep(2000); driver.findElement(By.xpath("//input[@name='b2']")).click(); Thread.sleep(2000); System.out.println(driver.switchTo().alert().getText()); Thread.sleep(2000); driver.switchTo().alert().accept(); driver.findElement(By.xpath("//input[@name='b3']")).click(); Thread.sleep(2000); driver.switchTo().alert().accept();}
示例2:Alert(driver),dismisswindows
測試連接:http://sahitest.com/demo/confirmTest.htmapi
@Test public void test4() throws InterruptedException{ driver.get("http://sahitest.com/demo/confirmTest.htm"); driver.findElement(By.xpath("//input[@name='b1']")).click(); System.out.println(driver.switchTo().alert().getText()); Thread.sleep(1000); driver.switchTo().alert().dismiss(); }
示例3: switch_to.alert,send_keys(keysToSend)
測試連接:http://sahitest.com/demo/promptTest.htm
@Test public void test4() throws InterruptedException{ driver.get("http://sahitest.com/demo/promptTest.htm"); driver.findElement(By.xpath("//input[@name='b1']")).click(); driver.switchTo().alert().sendKeys("Hello world"); Thread.sleep(1000); driver.switchTo().alert().accept();}
問題:汽車之家的彈窗,是什麼類型
3.切換到iFrame/Frame
web應用中常常會遇到frame/iframe表單嵌套頁面的應用,web driver只能在一個頁面對元素進行識別與定位,此時須要經過switch_to.frame()方法將當前定位的主體切換爲frame/iframe表單的內嵌頁面中。driver.switchTo().defaultContent()跳回最外層的頁面。driver.switchTo().parentFrame();返回上一級頁面
@Test public void frame() throws InterruptedException{ driver.get("http://sahitest.com/demo/framesTest.htm"); driver.switchTo().frame("top"); //根據惟一的標示,如id,name進入frame WebElement shadow=driver.findElement(By.xpath("//a[@href='shadowRoot.html']")); System.out.println(shadow.getText()); driver.switchTo().parentFrame(); //返回上一層 //driver.switchTo().frame("/html/frameset/frame[2]") WebElement show2 = driver.findElement(By.xpath("/html/frameset/frame[2]")); //先找到元素,再進入表單 driver.switchTo().frame(show2); System.out.println(driver.findElement(By.xpath("//a[@href=\"selectTest.htm\"]")).getText()); driver.switchTo().defaultContent();} //返回最外層
2、cookie處理
有時咱們須要驗證瀏覽器中cookie是否正確,由於基於真是cookie的測試是沒法經過白盒和集成測試的。Web Driver提供了操做cookie的相關方法,能夠讀取、添加和刪除cookie信息。
1.獲取cookie
1.1獲取全部的cookie
@Test public void cookieTest() throws InterruptedException{ driver.get("http://www.baidu.com"); System.out.println(driver.manage().getCookies()); } //獲取的cookie爲一個字典
1.2 對cookie進行迭代
for(Cookie cookie:driver.manage().getCookies()){ System.out.print("name:"+cookie.getName()+"\t"); System.out.print("Domain:"+cookie.getDomain()+"\t"); System.out.print("Expiry:"+cookie.getExpiry()+"\t"); System.out.print("value:"+cookie.getValue()+"\t"); System.out.println("path:"+cookie.getPath()); }
1.3 根據name獲取某個cookie
@Test public void cookieTest() throws InterruptedException{ driver.get("http://www.autohome.com"); Cookie cookie = driver.manage().getCookieNamed("area"); System.out.println(cookie); }
2.添加cookie
Cookie cookie = new Cookie("","","",null)
driver.manage().addCookie(cookie)
@Test public void cookieTest() throws InterruptedException{ driver.get("http://www.autohome.com"); //獲取異常,打印日誌 try{ driver.switchTo().alert().dismiss(); } catch (Exception e){ Reporter.log("No alert displayed",true); } //添加cookie Cookie addcookie = new Cookie("zhangsan","lisi"); driver.manage().addCookie(addcookie); for(Cookie cookie:driver.manage().getCookies()){ System.out.print("name:"+cookie.getName()+"\t"); System.out.println("value:"+cookie.getValue()+"\t"); } }
2.刪除cookie
2.1 刪除單個cookie
@Test public void cookieTest() throws InterruptedException{ driver.get("http://www.autohome.com"); Cookie cookie = driver.manage().getCookieNamed("area"); System.out.println(cookie.getName()+"\t"+cookie.getValue()); driver.manage().deleteCookie(cookie); for(Cookie icookie:driver.manage().getCookies()){ System.out.println(icookie.getName()+"\t"+icookie.getValue()); } //也能夠直接按照name刪除cookie driver.manage().deleteCookieNamed("ahpau"); }
2.2 刪除所有cookie
public void cookieTest() throws InterruptedException{ driver.get("http://www.autohome.com"); driver.manage().deleteAllCookies(); System.out.println(driver.manage().getCookies()); }
3、執行JavaScript
document.getElementById("ibm-masthead").style.display='none';
arguments[0].setAttribute('style',arguments[1]);
arguments[0].scrollIntoView(true);
document.documentElement.scrollTop=500
document.getElementById(i).style.display ='block'; //獲取當前頁面裏面id爲i的標籤,改變該標籤的樣式,使其滿框顯示。
document.getElementById(i).style.display ='none'; //獲取當前頁面裏面id爲i的標籤,改變該標籤的樣式,使其不顯示。
document.getElementById(i).style.display ='inline'; //獲取當前頁面裏面id爲i的標籤,改變該標籤的樣式,使其顯示。
@Test public void testJS(){ driver.get("http://www.baidu.com"); WebElement img = driver.findElement(By.xpath("//*[@id=\"cp\ JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("arguments[0].scrollIntoView(true);",img);}
返回返回值
return arguments[0].getText();
return documents.readyState;
return window.innerWidth
return document.documentElement.scrollTop
@Test public void testJS(){ driver.get("http://www.baidu.com"); JavascriptExecutor js = (JavascriptExecutor)driver; Object top=js.executeScript("return document.documentElement.scrollTop") ; System.out.println((long)top); }
執行JavaScript腳本http://lijingshou.iteye.com/blog/2018929
1.初始化
JavascriptExecutor js = (JavascriptExecutor)driver;
2.直接傳入Javascript代碼
js.executeScript("window.document.getElementById('su').click()";
3.傳入WebElement執行js腳本
//百度首頁點擊百度一下
WebElement element = driver.findElement(By.id("su"));
js.executeScript("arguments[0].click();", element);
//
js.executeScript("arguments[0].onclick=function(){alert('This is my alert!');}", element)
//指定的DIV就新增(修改)了 style {height: 1000px}的屬性
WebElement div = driver.findElemnt(By.id("myDiv"));
jse.executeScript("arguments[0].setAttribute('style', arguments[1])", div, "height: 1000px");
4、actions
@Test public void cookieTest() throws InterruptedException{ driver.get("http://www.baidu.com"); Actions action = new Actions(driver); action.doubleClick(driver.findElement(By.xpath("//a[@name='tj_trmap']"))); }
5、網頁截圖
須要jar包http://commons.apache.org/proper/commons-io/download_io.cgi
下載Binaries文件
若是下載commons-io-*.tar.gz,須要先解壓tar -zxvf commons-io-*.tar.gz
導入jar包
file-project structure-添加-JARs and directories,添加解壓後的目錄
@Test public void screenshotTest() throws IOException { driver.get("http://www.baidu.com"); String screenpath = System.getProperty("user.dir")+"/src/screenshot/"; System.out.println(screenpath); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmmss"); String time = dateFormat.format(Calendar.getInstance().getTime()); File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(srcFile,new File(screenpath,time+".png")); //FileUtils.copyFile(srcFile,new File(screenpath,time+".png")); }
結果:
6、上傳下載
沒講
https://seleniumhq.github.io/selenium/docs/api/java/overview-summary.html
7、顯式等待、隱式等待
等待的方式有三種:顯示等待、隱私等待、線程休眠
1. 顯示等待 針對於某個元素的明確等待
WebDriverWait wait = new WebDriverWait(driver,15);
wait.unitl(ExpectedConditions.visibilityOfElementLocated(By.id("kw")));
@Test public void waitfor(){ driver.get("http://www.baidu.com"); driver.findElement(By.id("kw")).sendKeys("selenium"); driver.findElement(By.id("su")).click(); //顯式等待,每500毫秒檢查元素是否存在;超過30秒沒有發現,就報異常 By result = By.cssSelector("span.nums_text"); WebDriverWait wait = new WebDriverWait(driver,30); wait.until(ExpectedConditions.visibilityOfElementLocated(result)); String actureResult = driver.findElement(result).getText(); String expectResult="百度爲您找到相關結果"; Assert.assertTrue(actureResult.contains(expectResult)); }
2. 隱式等待 經過 必定的時長等待頁面上某元素加載完成,默認設置爲0。可設置爲全局等待
webDriver driver;
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
3. 線程休眠
Thread.sleep(5000)
8、數據驅動
1. 根據二維數組輸入內容
package testcase; import org.apache.commons.io.FileUtils; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.*; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.concurrent.TimeUnit; public class dataProvider { @DataProvider public static Object[][] getTestData(){ Object[][] o = new Object[2][1]; o[0][0] = "selenium"; o[1][0] = "appium"; return o; } @Test(dataProvider = "getTestData") public void seartchTest(String searchKey) throws IOException { String chromePath = System.getProperty("user.dir") + "/src/main/java/drivers/chromedriver"; String screenpath = System.getProperty("user.dir")+ "/src/screenshot/"; WebDriver driver ; System.setProperty("webdriver.chrome.driver", chromePath); driver=new ChromeDriver(); driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS); driver.get("http://www.baidu.com"); driver.findElement(By.id("kw")).sendKeys(searchKey); driver.findElement(By.id("su")).click(); By result = By.cssSelector("span.nums_text"); Assert.assertTrue(driver.findElement(result).isDisplayed()); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); String time = dateFormat.format(Calendar.getInstance().getTime()); File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(srcFile,new File(screenpath,time+".png")); driver.close(); } }
2. 從excel文件中導入數組
//須要把腳本轉化爲excel驅動的模式 import java.io.File; import java.io.FileInputStream; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFSheet; public class SeleniumWork1 { public static void main(String[] args){ try{ File src = new File("/Users/chenshanju/Desktop/testerhome/java.xlsx"); FileInputStream fis = new FileInputStream(src); @SuppressWarnings("resource") XSSFWorkbook wb = new XSSFWorkbook(fis); XSSFSheet sh1 = wb.getSheetAt(0); System.out.println(sh1.getRow(0).getCell(0).getStringCellValue()); System.out.println(sh1.getRow(3).getCell(1).getStringCellValue()); int rowInExcel = sh1.getPhysicalNumberOfRows(); int columnInExcel = sh1.getRow(0).getPhysicalNumberOfCells(); System.out.println(rowInExcel+"\t"+columnInExcel); String[][] obj = new String[rowInExcel][columnInExcel]; for(int row=0;row <rowInExcel;row++){ for(int col=0;col<columnInExcel;col++){ obj[row][col]=sh1.getRow(row).getCell(col).getStringCellValue(); System.out.println(obj[row][col]); } } }catch (Exception e){ System.out.println(e.getMessage()); } } }