標籤:方法 ogr interrupt assert sub find web ima str
問題: selenium啟動firefox的時候,會使用一個全新的profile作為啟動的profile,即手工在firefox中的設定都無法使用。
解決: 找到手動啟動firefox時的profile目錄,測試程式中通過FirefoxProfile傳遞給WebDriver
1. 查看profile目錄
命令列方式,進入firefox安裝目錄(多為: C:\Program Files (x86)\Mozilla Firefox),執行
firefox.ext -P
或
firefox.exe -ProfileManager
彈出profile管理畫面,滑鼠移到profile名上,會顯示其路徑
也可建立profile目錄,從此對話方塊啟動該profile的firefox,設定信任網站
2. 測試程式:
1 @Test 2 public void test() { 3 System.setProperty("webdriver.gecko.driver", "E:/selenium/geckodriver.exe"); 4 5 //指向firefox的profile目錄 6 FirefoxProfile profile = new FirefoxProfile(new File("C:/Users/me/AppData/Roaming/Mozilla/Firefox/Profiles/mmi7kyn4.default")); 7 profile.setAcceptUntrustedCertificates(true); 8 9 //使用指定profile啟動10 WebDriver driver = new FirefoxDriver(profile);11 driver.get("https://www.abcd.com");12 13 //輸入使用者名稱,密碼,並提交14 WebElement userId = driver.findElement(By.cssSelector("input[name=‘userId‘]"));15 userId.sendKeys("username");16 WebElement password = driver.findElement(By.cssSelector("input[name=‘password‘]"));17 password.sendKeys("pasword");18 19 WebElement submit = driver.findElement(By.cssSelector("button"));20 submit.click();21 22 //稍微等待應答23 try {24 Thread.sleep(3000);25 } catch (InterruptedException e) {26 e.printStackTrace();27 }28 29 Assert.assertEquals("XXX", driver.getTitle());30 driver.quit();31 }
關於延時等待的幾個方法:
1) Thread.sleep() , 最笨的方法,但有時也很實用
2) 隱示等待,指當要尋找元素沒有馬上出現時,告訴WebDriver查詢Dom一定時間。預設值是0,但是設定之後,這個時間將在WebDriver對象執行個體整個生命週期都起作用。
WebDriver dr = new FirefoxDriver();
dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
3) 使用javascript
WebElement element = driver.findElement(By.xpath(test));
((JavascriptExecutor)driver).executeScript("arguments[0].style.border="5px solid yellow"",element);
4) 顯示等待,推薦使用。
WebDriverWait wait = new WebDriverWait(dr, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("kw")));
顯式等待可以自訂等待的條件,用於更加複雜的頁面等待條件
(1)元素可用和可被單擊:elementToBeClickable(By locator)
(2)元素處於被選中狀態:elementToBeSelected(WebElement element)
(3)元素存在:presenceOfElementLocated(By locator)
(4)元素中包含特定的文本:textToBePresentInElement(By locator)
(5)頁面元素值:textToBePresentInElementValue(By locator, java.lang.String text)
(6)標題 (title):titleContains(java.lang.String title)
參考地址:
http://www.cnblogs.com/lelelong/p/5523444.html
http://blog.sina.com.cn/s/blog_71bc9d680102wr4o.html
selenium學習筆記(2) 測試https網站