robot framework筆記(三):擴展SeleniumLibrary庫 (自定義關鍵字)


(一)自定義和瀏覽器相關的關鍵字

PYTHON 版本:3.6,不同的版本可能有區別,自己注意下。

以下代碼GitHub 版本庫地址: https://github.com/blairwind/blog_rf

      SeleniumLibrary的擴展文檔中提供了3種增加SeleniumLibrary功能的方式。

  (1)Plugin API

  (2)EventFiringWebDriver

  (3)Extending SeleniumLibrary(實際就是繼承SeleniumLibrary庫)

  這里采用繼承SeleniumLibrary庫的方式。

目錄結構如下:這里我們將上一篇中說到的關鍵字加進來

 BlogSeleniumLibrary.__init__.py  的代碼

# #-*-coding:utf-8-*-
#
from robot.libraries import BuiltIn
from SeleniumLibrary.base import DynamicCore
from SeleniumLibrary.keywords import (AlertKeywords,
                                      BrowserManagementKeywords,
                                      CookieKeywords,
                                      ElementKeywords,
                                      FormElementKeywords,
                                      FrameKeywords,
                                      JavaScriptKeywords,
                                      RunOnFailureKeywords,
                                      ScreenshotKeywords,
                                      SelectElementKeywords,
                                      TableElementKeywords,
                                      WaitingKeywords,
                                      WebDriverCache,
                                      WindowKeywords)
from SeleniumLibrary.locators import ElementFinder
from SeleniumLibrary.utils import Deprecated, LibraryListener, timestr_to_secs
from  SeleniumLibrary import SeleniumLibrary

from BlogSeleniumLibrary.keywords import (
                                            KeyboardKeywords)


class  BlogSeleniumLibrary(SeleniumLibrary):


    def  __init__(self, timeout=5.0, implicit_wait=0.0,
                 run_on_failure='Capture Page Screenshot',
                 screenshot_root_directory=None):
        self.timeout = timestr_to_secs(timeout)
        self.implicit_wait = timestr_to_secs(implicit_wait)
        self.speed = 0.0
        self.run_on_failure_keyword \
            = RunOnFailureKeywords.resolve_keyword(run_on_failure)
        self._running_on_failure_keyword = False
        self.screenshot_root_directory = screenshot_root_directory
        libraries = [
            AlertKeywords(self),
            BrowserManagementKeywords(self),
            CookieKeywords(self),
            ElementKeywords(self),
            FormElementKeywords(self),
            FrameKeywords(self),
            JavaScriptKeywords(self),
            RunOnFailureKeywords(self),
            ScreenshotKeywords(self),
            SelectElementKeywords(self),
            TableElementKeywords(self),
            WaitingKeywords(self),
            WindowKeywords(self),
            KeyboardKeywords(self)
        ]
        self._drivers = WebDriverCache()
        DynamicCore.__init__(self, libraries)
        self.ROBOT_LIBRARY_LISTENER = LibraryListener()
        self._element_finder = ElementFinder(self)

    _speed_in_secs = Deprecated('_speed_in_secs', 'speed')
    _timeout_in_secs = Deprecated('_timeout_in_secs', 'timeout')
    _implicit_wait_in_secs = Deprecated('_implicit_wait_in_secs',
                                        'implicit_wait')
    _run_on_failure_keyword = Deprecated('_run_on_failure_keyword',
                                         'run_on_failure_keyword')

 BlogSeleniumLibrary.keywords.__init__.py  的代碼

from .keyboard import KeyboardKeywords

BlogSeleniumLibrary.keywords.keyboard.py  的代碼

 1 from SeleniumLibrary.base import keyword, LibraryComponent
 2 from selenium.webdriver.chrome.options import Options
 3 from  selenium import webdriver
 4 from SeleniumLibrary.locators import WindowManager
 5 
 6 class KeyboardKeywords(LibraryComponent):
 7 
 8     def __init__(self, ctx):
 9         LibraryComponent.__init__(self, ctx)
10         self._window_manager = WindowManager(ctx)
11 
12     @keyword()
13     def get_chrome_options(self, downloads_path):
14         '''
15         自定義chrome啟動參數
16         :param downloads_path: 設置默認的文件下載路徑
17         :return:
18         '''
19         chrome_options = Options()
20         prefs = {
21             "download.default_directory": str(downloads_path),
22         }
23         chrome_options.add_experimental_option('prefs', prefs)  # 設置默認的文件下載路徑
24         chrome_options.add_argument('disable-infobars')  # chrome76以下禁用chrome受自動軟件控制
25         # 下面2行chrome76及以上禁用chrome受自動軟件控制
26         chrome_options.add_experimental_option("useAutomationExtension", False)
27         chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
28         return chrome_options
29 
30     @keyword()
31     def open_browser_new(self, alias=None,**kwargs):
32         '''
33         :return:
34         '''
35         desired_caps = {
36             "platform": kwargs["platform"],  #操作系統
37             # "platform":"LINUX",
38             "browserName": kwargs["browserName"],  #瀏覽器
39             "version":kwargs["version"]  #瀏覽器版本
40         }
41 
42         driver = webdriver.Remote(command_executor=kwargs["remote_url"],
43                                   desired_capabilities=desired_caps,
44                                   options=kwargs["chrome_options"])
45         return self.ctx.register_driver(driver,alias)

 

最后,在RF中導入繼承SeleniumLibrary后新建的庫就行了,如下:

注意在RF中python 包名和類名一樣的的話,導入庫的時候就只需要填包名就行了,RF可以直接識別到。不一樣的話就還需要加上.class名稱,下面這個是不使用selenium grid的版本

*** Settings ***
Library                     BlogSeleniumLibrary     #注意這一行不一樣
Suite Teardown              CLOSE BROWSER

*** Variables ***
${browser}            Chrome
${login_url}          https://account.cnblogs.com/signin


*** Test Cases ***
登錄-XXXXXX
    登錄-打開瀏覽器並進入登錄頁面


*** Keywords ***
登錄-打開瀏覽器並進入登錄頁面
    ${options}=  GET CHROME OPTIONS  D:/projectname/testdata/downloads
    CREATE WEBDRIVER  ${browser}  chrome_options=${options}
    GO TO  ${login_url}
    SET SELENIUM IMPLICIT WAIT  10
    MAXIMIZE BROWSER WINDOW

(二)如果要使用selenium grid呢

  上篇中說到在RF中使用selenium grid ,在這里說明下。(為什么不使用RF自帶的open browser,原因是個人覺得這種方式更方便添加不同的參數。)可以看到這里新加了一個關鍵字

當然,既然用了selenium grid,肯定會考慮並發執行用例,以及合並測試報告的問題,這里暫不考慮這個。

 1     @keyword()
 2     def open_browser_new(self, alias=None,**kwargs):
 3         '''
 4         :return:
 5         '''
 6         desired_caps = {
 7             "platform": kwargs["platform"], #操作系統
 8             # "platform":"LINUX",
 9             "browserName": kwargs["browserName"], #瀏覽器
10             "version":kwargs["version"]  #瀏覽器版本
11         }
12 
13         driver = webdriver.Remote(command_executor=kwargs["remote_url"],
14                                   desired_capabilities=desired_caps,
15                                   options=kwargs["chrome_options"])
16         return self.ctx.register_driver(driver,alias)

在RF中調用這個關鍵字去啟動瀏覽器就行了。當然前提是你要有一個配好的selenium grid環境,remote_url填自己selenium grid的地址。

 1 *** Settings ***
 2 Library                     BlogSeleniumLibrary
 3 Suite Teardown              CLOSE BROWSER
 4 
 5 *** Variables ***
 6 ${platform}          WINDOWS
 7 ${browser}            chrome
 8 ${version}            79
 9 ${remote_url}         http://192.168.63.1:4444/wd/hub
10 ${login_url}          https://account.cnblogs.com/signin
11 
12 
13 *** Test Cases ***
14 登錄-XXXXXX
15     登錄-打開瀏覽器並進入登錄頁面
16 
17 
18 *** Keywords ***
19 登錄-打開瀏覽器並進入登錄頁面
20     ${options}=  GET CHROME OPTIONS  D:/projectname/testdata/downloads   #這里是寫死的路徑,實際項目中應該動態去獲取工程路徑/testdata/downloads 
21     OPEN BROWSER NEW  platform=${platform}  browserName=${browser}  version=${version}
22                       ...  chrome_options=${options}  remote_url=${remote_url}
23     GO TO  ${login_url}
24     SET SELENIUM IMPLICIT WAIT  10
25     MAXIMIZE BROWSER WINDOW

 

 

(三)自定義和瀏覽器無關的關鍵字(例如:和數據庫相關的關鍵字)

如果有一些關鍵字用不到selenium 的webdriver,可以考慮獨立出來。例如數據庫相關的關鍵字,實現方式以及在RF中的導入方式,可以參考上一篇的mykeyword 關鍵字的寫法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM