selenium webdriver原理

雖說UI自動化成本高,維護難度大,但應用廣泛,在一定場景下還是非常強有力的工具,所以說還是有必要了解一下的

文章標題為 selenium webdriver 但實際上講的都是webdriver,歷史就不講了,直接介紹原理


先做一個實驗

  • 安裝好python2.7以及selenium和requests
pip install selenium
pip install requests
  • 下載好chromedriver,放到環境變量里,注意要和chrome瀏覽器版本對上,然后執行chromedriver
sun@sun:~ ? chromedriver
Starting ChromeDriver 2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8) on port 9515
Only local connections are allowed.

可以看出,上面的chromedriver啟動后在本地啟動了一個WEB服務,端口是9515,但只能用于本地鏈接

  • 執行代碼
# coding=utf-8
import requests
import time

capabilities = {
    "capabilities": {
        "alwaysMatch": {
            "browserName": "chrome"
        },
        "firstMatch": [
            {}
        ]
    },
    "desiredCapabilities": {
        "platform": "ANY",
        "browserName": "chrome",
        "version": "",
        "chromeOptions": {
            "args": [],
            "extensions": []
        }
    }
}

# 打開瀏覽器 http://127.0.0.1:9515/session
res = requests.post('http://127.0.0.1:9515/session', json=capabilities).json()
session_id = res['sessionId']

# 打開百度
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)

# 關閉瀏覽器,刪除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.

上面是官網的介紹,我來轉義一下:

  • selenium 2.0最重要的特性就是集成了WebDrvier API,WebDriver除了解決一些Selenium-RC API的不足外,旨在提供更簡單,更簡潔的編程接口
  • Selenium-WebDrivers為更好的支持動態頁面(也就是ajax,不刷新頁面改變DOM)而開發
  • 目標是提供一套精心設計的面向對象的API,為現代WEB應用自動化測試提供更好的支持

總結一下,就是說它是為了更好的支持動態頁面,更簡單易用的編程接口,如果你感覺覺得有點抽像,我們接著往下看

webdriver是怎么運行的

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直接調用了瀏覽器對自動化測試的原生接口,具體怎么調用,取決于你使用的瀏覽器(chrome使用chromedriver,IE使用iedriver),但重要的是最終提供出來的接口是一樣的

再簡化下這個概念:

  • 每個瀏覽器都有自己自動化測試接口,如打開網頁,點擊等
  • 每個瀏覽器自己的webdriver實現,如chromedriver iedriver都封裝了這些自動化測試接口,然后把這些操作以一個標準web restfull api暴露出來

大家看下面的圖:

舉個栗子:chromedriver

各語言實現

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容