Selenium webdriver Java 高階應用

微微微笑發表於2015-07-11

對於這一段還蠻有感慨的,只想說,程式碼還是需要自己去敲的。

1. 改變使用者代理

import org.junit.AfterClass; 
import org.junit.BeforeClass; 
import org.junit.Test; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.firefox.FirefoxDriver; 
import org.openqa.selenium.firefox.FirefoxProfile; 

public class ProxyTest { 
static WebDriver driver; 

@BeforeClass 
public static void beforeClass(){ 
//代理的IP和埠 
String proxyIP="192.168.12.0"; 
int proxyPort=80; 
FirefoxProfile profile=new FirefoxProfile(); 
//使用代理 
profile.setPreference("network.proxy.type", 1); 
//配置“HTTP代理:(N)” 
profile.setPreference("network.proxy.http", proxyIP); 
profile.setPreference("network.proxy.http_prot", proxyPort); 
//選中 “為所有協議使用相同代理(S)” 選框 
profile.setPreference("network.proxy.share_proxy_settings", true); 
//配置“不使用代理:(N)”文字框 
profile.setPreference("network.proxy.no_proxies_on", "localhost, 127.0.0.1"); 
//以代理的方式啟動火狐 
driver=new FirefoxDriver(profile); 
} 

@Test 
public void test() { 
driver.get("http://www.baidu.com"); 
} 

@AfterClass 
public static void afterClass(){ 
//driver.quit(); 
} 
} 

執行之後,在開啟的火狐上檢視代理設定(選項->高階->網路->連線->設定),顯示如下:

https://i.iter01.com/images/58053ccb57f0d83c955a2554afea78a7b69d2113695d2bbb157a6e2e328da0ae.png

友情提示:測試完之後一定要改回來。預設是“使用系統代理設定”。

2.讀取Cookies 

增加cookie:

Cookie cookie = new Cookie("key", "value");

driver.manage().addCookie(cookie);

獲取cookie的值:

Set<Cookie> allCookies = driver.manage().getCookies();

根據某個cookie的name獲取cookie的值:

driver.manage().getCookieNamed("cookieName");

刪除cookie:  

driver.manage().deleteCookieNamed("CookieName");

driver.manage().deleteCookie(loadedCookie);

driver.manage().deleteAllCookies();

下面是一個例子:

import java.util.Set;  
import org.junit.After;  
import org.junit.Before;  
import org.junit.Test;  
import org.openqa.selenium.Cookie;  
import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.firefox.FirefoxDriver;  
  
public class CookieTest {  
    WebDriver driver;  
      
    @Before  
    public void setUp() throws Exception {  
        driver=new FirefoxDriver();  
    }  
  
    @After  
    public void tearDown() throws Exception {  
        driver.quit();  
    }  
  
    @Test  
    public void test() {  
        printCookie();  
        //新增一個cookie  
        Cookie cookie=new Cookie("s","selenium");  
        driver.manage().addCookie(cookie);  
        printCookie();  
        //刪除一個cookie  
        driver.manage().deleteCookie(cookie);   //driver.manage().deleteCookieNamed("s");也可以  
        printCookie();  
    }  
      
    public void printCookie(){  
        //獲取並列印所有的cookie  
        Set<Cookie> allCookies=driver.manage().getCookies();  
          
        System.out.println("----------Begin---------------");  
        for(Cookie c:allCookies){  
            System.out.println(String.format("%s->%s",c.getName(),c.getValue()));  
        }  
        System.out.println("----------End---------------");  
    }  
}  

執行結果顯示為:

----------Begin---------------
----------End---------------
----------Begin---------------
s->selenium
----------End---------------
----------Begin---------------
----------End---------------
可以看到新增cookie之前,系統的cookie為空。之後成功新增了cookie(s,selenium)並且最後成功刪除。

3. 呼叫Java Script

selenium提供了executeScriptexecuteAsyncScript兩個方法來處理JS呼叫的問題。其中executeScript是同步方法,用它執行js程式碼會阻塞主執行緒執行,直到js程式碼執行完畢;executeAsyncScript方法是非同步方法,它不會阻塞主執行緒執行。

import org.junit.Test;  
import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.firefox.FirefoxDriver;  
import org.openqa.selenium.JavascriptExecutor;  
  
public class JSTest {  
    @Test  
    public void test() {  
        WebDriver driver=new FirefoxDriver();  
        driver.get("http://www.baidu.com");  
        JavascriptExecutor js=(JavascriptExecutor)driver;  
        js.executeScript("document.getElementById(\"kw\").value=\"selenium\"");  
        //利用js程式碼獲取百度搜尋框內文字  
        String keyword = (String) (js.executeScript("var input = document.getElementById(\"kw\").value;return input"));  
        System.out.println(keyword);  
        driver.quit();  
    }  
}  

執行結果:

selenium

4. Webdriver截圖

import java.io.File;  
import java.io.IOException;  
import org.apache.commons.io.FileUtils;  
import org.junit.Test;  
import org.openqa.selenium.OutputType;  
import org.openqa.selenium.TakesScreenshot;  
import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.firefox.FirefoxDriver;  
  
public class ScreenShotTest {  
  
    @Test  
    public void test() {  
        WebDriver driver=new FirefoxDriver();  
        driver.get("http://www.baidu.com");  
        screenShot("selenium.jpg", (TakesScreenshot)driver);  
        driver.quit();  
    }  
      
    public static void screenShot(String name,TakesScreenshot driver){  
        String savaPath=System.getProperty("user.dir");  
        File sourceFile=driver.getScreenshotAs(OutputType.FILE);  
        try{  
            System.out.println("Begin saving screenshot to path:"+savaPath);  
            FileUtils.copyFile(sourceFile, new File(savaPath+"\\"+name));  
        } catch(IOException e){  
            System.out.println("Save screenshot failed!");  
            e.printStackTrace();  
        } finally{  
            System.out.println("Finish screenshot!");  
        }  
    }  
}  

執行結果:

Begin saving screenshot to path:D:\workspace_luna\SeleniumDemo
Finish screenshot!

由於eclipse的workspace不一樣,會導致上面的路徑不一樣。不過沒關係,我們開啟對應的路徑就可以看到selenium.jpg。開啟以後是百度首頁的截圖。

5. 頁面等待

因為Load頁面需要一段時間,如果頁面還沒載入完就查詢元素,必然是查詢不到的。最好的方式,就是設定一個預設等待時間,在查詢頁面元素的時候如果找不到就等待一段時間再找,直到超時。Webdriver提供兩種方法,一種是顯性等待,另一種是隱性等待。

顯性等待:

顯示等待就是明確的要等到某個元素的出現或者是某個元素的可點選等條件,等不到,就一直等,除非在規定的時間之內都沒找到,那麼就跳出Exception.

new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.id("kw")));  

當然也可以自己重寫內部類:

WebElement e = (new WebDriverWait( driver, 10)).until(  
        new ExpectedCondition< WebElement>(){  
            @Override  
            public WebElement apply( WebDriver d) {  
                return d.findElement(By.linkText("Selenium_百度百科"));  
            }  
        });  

 

下面的例子是:開啟百度,搜尋“selenium",等待搜尋結果裡出現“Selenium_百度百科”的時候點選該連結。

import org.junit.Test;  
import org.openqa.selenium.By;  
import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.WebElement;  
import org.openqa.selenium.firefox.FirefoxDriver;  
import org.openqa.selenium.support.ui.ExpectedCondition;  
import org.openqa.selenium.support.ui.ExpectedConditions;  
import org.openqa.selenium.support.ui.WebDriverWait;  
  
public class ExplicitWaitTest {  
    @Test  
    public void test() {  
        WebDriver driver=new FirefoxDriver();  
        driver.get("http://www.baidu.com");  
        driver.findElement(By.id("kw")).sendKeys("selenium");  
        driver.findElement(By.id("su")).click();  
        //方法一  
        //new WebDriverWait(driver,10).until(ExpectedConditions.presenceOfElementLocated(By.linkText("Selenium_百度百科")));  
        //driver.findElement(By.linkText("Selenium_百度百科")).click();  
        //方法二  
        WebElement e = (new WebDriverWait( driver, 10)).until(  
                new ExpectedCondition< WebElement>(){  
                    @Override  
                    public WebElement apply( WebDriver d) {  
                        return d.findElement(By.linkText("Selenium_百度百科"));  
                    }  
                }  
            );  
        e.click();  
          
        driver.quit();  
    }  
}  

執行的話是通過的,但是如果中間不顯示等待的話,直接查詢就會fail。

 

隱性等待:

隱形等待只是等待一段時間,元素不一定要出現,只要時間到了就會繼續執行。

driver.manage().timeouts().implicitlyWait(second, TimeUnit.SECONDS);  

還是上面的例子,用隱性等待寫就是:

import java.util.concurrent.TimeUnit;  
import org.junit.Test;  
import org.openqa.selenium.By;  
import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.firefox.FirefoxDriver;  
  
public class ImplicitWaitTest {  
    @Test  
    public void test() {  
        WebDriver driver=new FirefoxDriver();  
        driver.get("http://www.baidu.com");  
        driver.findElement(By.id("kw")).sendKeys("selenium");  
        driver.findElement(By.id("su")).click();  
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);  
        driver.findElement(By.linkText("Selenium_百度百科")).click();  
          
        driver.quit();  
    }  
}  

執行結果還是通過的。不過個人覺得看起來跟笨方法”Thread.sleep()"差不多,只不多比它更高效了而已。

相關文章