selenium之操做ChromeDriver

selenium操做chrome瀏覽器須要有ChromeDriver驅動來協助。html

什麼是ChromeDriver?web

ChromeDriver是Chromium team開發維護的,它是實現WebDriver有線協議的一個單獨的服務。ChromeDriver經過chrome的自動代理框架控制瀏覽器,ChromeDriver只與12.0.712.0以上版本的chrome瀏覽器兼容。chrome

那麼要想selenium成功的操做chrome瀏覽器須要經歷以下步驟:api

一、下載ChromeDriver驅動包(下載地址:http://chromedriver.storage.googleapis.com/index.html?path=2.7/瀏覽器

 

注意閱讀note.txt下載與本身所使用瀏覽器一致版本的驅動包。app

二、指定ChromeDriver所在位置,能夠經過兩種方法指定:框架

1)經過配置ChromeDriver.exe位置到path環境變量實現。測試

2)經過webdriver.chrome.driver.系統屬性實現。實現代碼以下:ui

System.setProperty("webdriver.chrome.driver", "C:\\Documents and Settings\\Administrator\\Local Settings\\Application Data\\Google\\Chrome\\Application\\chromedriver.exe");

三、最後須要作的就是建立一個新的ChromeDriver的實例。google

WebDriver driver = new ChromeDriver();
driver.get("http://www.baidu.com/"); 

至此咱們就能夠經過chrome瀏覽器來執行咱們的自動化代碼了。

完整實例代碼以下:

public static void main(String[] args) {

           // TODO Auto-generated method stub

//設置訪問ChromeDriver的路徑

System.setProperty("webdriver.chrome.driver", "C:\\Documents and Settings\\Administrator\\LocalSettings\\Application Data\\Google\\Chrome\\Application\\chromedriver.exe");

           WebDriver driver = new ChromeDriver();

           driver.get("http://www.baidu.com/");

 

}

btw:

chrome瀏覽器在各個系統默認位置:

OS Expected Location of Chrome
Linux /usr/bin/google-chrome1
Mac /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome
Windows XP %HOMEPATH%\Local Settings\Application Data\Google\Chrome\Application\chrome.exe
Windows Vista C:\Users\%USERNAME%\AppData\Local\Google\Chrome\Application\chrome.exe

 

 

執行以上代碼你會發現ChromeDriver僅是在建立是啓動,調用quit時關閉瀏覽器,ChromeDriver是輕量級的服務若在一個比較大的測試套件中頻繁的啓動關閉,會增長一個比較明顯的延時致使瀏覽器進程不被關閉的狀況發生,爲了不這一情況咱們能夠經過ChromeDriverService來控制ChromeDriver進程的生死,達到用完就關閉的效果避免進程佔用狀況出現(Running the server in a child process)。

具體實現以下:

ChromeDriverService service = new ChromeDriverService.Builder() .usingChromeDriverExecutable(new File("E:\\Selenium WebDriver\\chromedriver_win_23.0.1240.0\\chromedriver.exe")).usingAnyFreePort().build(); service.start(); driver = new ChromeDriver(); driver.get("http://www.baidu.com"); driver.quit(); // 關閉 ChromeDriver 接口 service.stop();
相關文章
相關標籤/搜索