雖說(shuō)UI自動(dòng)化成本高,維護(hù)難度大,但應(yīng)用廣泛,在一定場(chǎng)景下還是非常強(qiáng)有力的工具,所以說(shuō)還是有必要了解一下的
文章標(biāo)題為 selenium webdriver 但實(shí)際上講的都是webdriver,歷史就不講了,直接介紹原理
先做一個(gè)實(shí)驗(yàn)
- 安裝好python2.7以及selenium和requests
pip install selenium
pip install requests
- 下載好chromedriver,放到環(huán)境變量里,注意要和chrome瀏覽器版本對(duì)上,然后執(zhí)行chromedriver
sun@sun:~ ? chromedriver
Starting ChromeDriver 2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8) on port 9515
Only local connections are allowed.
可以看出,上面的chromedriver啟動(dòng)后在本地啟動(dòng)了一個(gè)WEB服務(wù),端口是9515,但只能用于本地鏈接
- 執(zhí)行代碼
# coding=utf-8
import requests
import time
capabilities = {
"capabilities": {
"alwaysMatch": {
"browserName": "chrome"
},
"firstMatch": [
{}
]
},
"desiredCapabilities": {
"platform": "ANY",
"browserName": "chrome",
"version": "",
"chromeOptions": {
"args": [],
"extensions": []
}
}
}
# 打開(kāi)瀏覽器 http://127.0.0.1:9515/session
res = requests.post('http://127.0.0.1:9515/session', json=capabilities).json()
session_id = res['sessionId']
# 打開(kāi)百度
requests.post('http://127.0.0.1:9515/session/%s/url' % session_id,
json={"url": "http://www.baidu.com", "sessionId": session_id})
time.sleep(3)
# 關(guān)閉瀏覽器,刪除session
requests.delete('http://127.0.0.1:9515/session/%s' % session_id, json={"sessionId": session_id})
什么是webdriver
The primary new feature in Selenium 2.0 is the integration of the WebDriver API. WebDriver is designed to provide a simpler, more concise programming interface in addition to addressing some limitations in the Selenium-RC API. Selenium-WebDriver was developed to better support dynamic web pages where elements of a page may change without the page itself being reloaded. WebDriver’s goal is to supply a well-designed object-oriented API that provides improved support for modern advanced web-app testing problems.
上面是官網(wǎng)的介紹,我來(lái)轉(zhuǎn)義一下:
- selenium 2.0最重要的特性就是集成了WebDrvier API,WebDriver除了解決一些Selenium-RC API的不足外,旨在提供更簡(jiǎn)單,更簡(jiǎn)潔的編程接口
- Selenium-WebDrivers為更好的支持動(dòng)態(tài)頁(yè)面(也就是ajax,不刷新頁(yè)面改變DOM)而開(kāi)發(fā)
- 目標(biāo)是提供一套精心設(shè)計(jì)的面向?qū)ο蟮腁PI,為現(xiàn)代WEB應(yīng)用自動(dòng)化測(cè)試提供更好的支持
總結(jié)一下,就是說(shuō)它是為了更好的支持動(dòng)態(tài)頁(yè)面,更簡(jiǎn)單易用的編程接口,如果你感覺(jué)覺(jué)得有點(diǎn)抽像,我們接著往下看
webdriver是怎么運(yùn)行的
Selenium-WebDriver makes direct calls to the browser using each browser’s native support for automation. How these direct calls are made, and the features they support depends on the browser you are using.
webdriver直接調(diào)用了瀏覽器對(duì)自動(dòng)化測(cè)試的原生接口,具體怎么調(diào)用,取決于你使用的瀏覽器(chrome使用chromedriver,IE使用iedriver),但重要的是最終提供出來(lái)的接口是一樣的
再簡(jiǎn)化下這個(gè)概念:
- 每個(gè)瀏覽器都有自己自動(dòng)化測(cè)試接口,如打開(kāi)網(wǎng)頁(yè),點(diǎn)擊等
- 每個(gè)瀏覽器自己的webdriver實(shí)現(xiàn),如chromedriver iedriver都封裝了這些自動(dòng)化測(cè)試接口,然后把這些操作以一個(gè)標(biāo)準(zhǔn)web restfull api暴露出來(lái)
大家看下面的圖: