0%

Browser自動化測試工具Selenium

Browser自動化測試工具Selenium - Selenium 初體驗

前言

前幾天與Software部門在進行測試網站某個功能性(每秒瀏灠一次網頁,共進行100次,查看第幾次開始得到http status code:403),因為我們部門長期都是使用Command-Line工作,因此為了方便用Shell Script簡單寫一個測試程式,測試結果與software部們不相同,了解之後,才知道他們是使用Browser 用手點方式測試。為了雙方測試環境一致性及客觀地顯示測試數據,本人有一個想法是否有支援程序化工具來控制Firefox或Chrome,經Google之後,很多網路上都推薦使用 Selenium,這項自動化測試工具。

建置selenium環境

  • 這邊範例使用 Windows 系統(win7 或 Win10 都可)
  • 這邊範例使用Python語言,Windows 預設沒有安裝Python,需要下載Python,選擇對應平台(x86 或 x86_64),下載後,執行下一步下一步的安裝方式,這邊就不展示。
  • 開啟命令提示字元, 打上 py 或 python,有跑出類似以下畫面表示python 安裝成功。
    py_windows
  • 安裝selenium。預設python 3 已有pip安裝python 第三方套件管理程式。
    1
    pip install selenium
  • 分別下載Firefox及Chrome的webdriver,為了方便使用,下載完放置在c:\

簡單執行自動執行Chrome

  • chromeDemo.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    from selenium import webdriver
    import time
    chrome_path="c:\chromedriver.exe"
    web=webdriver.Chrome(chrome_path)
    web.set_window_position(0,0)
    web.set_window_size(700,700)
    web.get('http://www.google.com')
    print(web.current_url)
    time.sleep(15)
    web.close()
  • 在命令提示字元 執行 chromeDemo.py
    1
    c:\>py chromeDemo.py

    簡單執行自動執Firefox

  • firefoxdemo.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.action_chains import ActionChains
    import time
    Firefox_path="c:\geckodriver.exe"
    web=webdriver.Firefox(executable_path=Firefox_path)
    web.set_window_position(0,0)
    web.set_window_size(700,700)
    ActionChains(web).key_down(Keys.F12).key_up(Keys.F12).perform()
    web.get('http://www.google.com')
    print(web.current_url)
    time.sleep(15)
    web.close()
  • 在命令提示字元 執行 firefoxdemo.py
    1
    c:\>py firefoxdemo.py

    範例 - 持續點擊某個網址

    以下使用chrome drive 來開啟Chrome Browser,並設定 Proxy相關設定(這邊我的內網有一台proxy: http://192.168.160.17:8082)之後,每隔1秒持續點擊 ifconfig.io
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    from selenium import webdriver
    import time
    PROXY='http://192.168.160.17:8082'

    webdriver.DesiredCapabilities.CHROME['proxy']={
    "httpProxy": PROXY,
    "ftpProxy": PROXY,
    "sslProxy": PROXY,
    "proxyType": "MANUAL",
    }
    chrome_path="./chromedriver.exe"
    with webdriver.Chrome(chrome_path) as web:
    web.set_window_position(0,0)
    web.set_window_size(700,700)
    for i in range(1,11):
    web.get('http://ifconfig.io')
    print('{}, URL: {}'.format(i,web.current_url))
    time.sleep(1)

    影片展示自動執行Firefox及Chrome

  • for Firefox
  • for Chrome

    參考資料

  • 英文-SeleniumHQ-官方
  • 英文-Selenium_Http proxies
  • Selenium with Python中文翻譯文檔
  • Python Selenium 常用方法總結
  • [Python] 使用Selenium在Google Chrome瀏覽器
  • [Python] Selenium 教學
  • 在Chrome上面使用Selenium WebDriver
  • Python爬蟲新手筆記

歡迎關注我的其它發布渠道