Ejemplo n.º 1
0
    def _make_new_browser(self,
                          url=None,
                          browser='firefox',
                          alias=None,
                          remote_url=False,
                          desired_capabilities=None,
                          ff_profile_dir=None,
                          options=None,
                          service_log_path=None,
                          devType=None):
        if is_truthy(remote_url):
            self.info("Opening browser '%s' to base url '%s' through "
                      "remote server at '%s'." % (browser, url, remote_url))
        else:
            self.info("Opening browser '%s' to base url '%s'." %
                      (browser, url))

        driver = self._make_driver(browser, desired_capabilities,
                                   ff_profile_dir, remote_url, options,
                                   service_log_path)
        driver = self._wrap_event_firing_webdriver(driver)
        index = self.ctx.register_driver(driver, alias)

        if is_truthy(url):
            driver.set_page_load_timeout(2)
            try:
                driver.get(url)

            except Exception:
                # self.info('heheheheheheh22222')
                # self.debug("Opened browser with session id %s but failed "
                #         "to open url '%s'." % (driver.session_id, url))
                # raise
                # driver.execute_script("window.stop()")
                import pyautogui, sys, pyperclip, time
                time.sleep(0.5)
                if devType != None:
                    pyautogui.hotkey('ctrl', 'r')
                else:
                    pyautogui.hotkey('tab')
                    time.sleep(0.1)
                    pyautogui.hotkey('tab')
                    time.sleep(0.1)
                    pyperclip.copy(url)
                    pyperclip.paste()
                    time.sleep(0.1)
                    pyautogui.hotkey('ctrl', 'v')
                    pyautogui.hotkey('enter')
                time.sleep(0.5)
        self.debug('Opened browser with session id %s.' % driver.session_id)
        driver.set_page_load_timeout(30)
        return index
Ejemplo n.º 2
0
    def element_should_not_contain(self,
                                   locator,
                                   expected,
                                   message=None,
                                   ignore_case=False):
        """Verifies that element ``locator`` does not contain text ``expected``.

        See the `Locating elements` section for details about the locator
        syntax.

        The ``message`` argument can be used to override the default error
        message.

        The ``ignore_case`` argument can be set to True to compare case
        insensitive, default is False.

        ``ignore_case`` argument new in SeleniumLibrary 3.1.
        """
        actual = self.find_element(locator).text
        expected_before = expected
        if is_truthy(ignore_case):
            actual = actual.lower()
            expected = expected.lower()
        if expected in actual:
            if is_noney(message):
                message = "Element '%s' should not contain text '%s' but " \
                          "it did." % (locator, expected_before)
            raise AssertionError(message)
        self.info("Element '%s' does not contain text '%s'." %
                  (locator, expected_before))
Ejemplo n.º 3
0
    def element_should_contain(self,
                               locator,
                               expected,
                               message=None,
                               ignore_case=False):
        """Verifies that element ``locator`` contains text ``expected``.

        See the `Locating elements` section for details about the locator
        syntax.

        The ``message`` argument can be used to override the default error
        message.

        The ``ignore_case`` argument can be set to True to compare case
        insensitive, default is False. New in SeleniumLibrary 3.1.

        ``ignore_case`` argument is new in SeleniumLibrary 3.1.

        Use `Element Text Should Be` if you want to match the exact text,
        not a substring.
        """
        actual = actual_before = self.find_element(locator).text
        expected_before = expected
        if is_truthy(ignore_case):
            actual = actual.lower()
            expected = expected.lower()
        if expected not in actual:
            if is_noney(message):
                message = "Element '%s' should have contained text '%s' but "\
                          "its text was '%s'." % (locator, expected_before, actual_before)
            raise AssertionError(message)
        self.info("Element '%s' contains text '%s'." %
                  (locator, expected_before))
Ejemplo n.º 4
0
    def element_text_should_not_be(self,
                                   locator,
                                   not_expected,
                                   message=None,
                                   ignore_case=False):
        """Verifies that element ``locator`` does not contain exact the text ``not_expected``.

        See the `Locating elements` section for details about the locator
        syntax.

        The ``message`` argument can be used to override the default error
        message.

        The ``ignore_case`` argument can be set to True to compare case
        insensitive, default is False.

        New in SeleniumLibrary 3.1.1
        """
        self.info("Verifying element '%s' does not contain exact text '%s'." %
                  (locator, not_expected))
        text = self.find_element(locator).text
        before_not_expected = not_expected
        if is_truthy(ignore_case):
            text = text.lower()
            not_expected = not_expected.lower()
        if text == not_expected:
            if is_noney(message):
                message = (
                    "The text of element '%s' was not supposed to be '%s'." %
                    (locator, before_not_expected))
            raise AssertionError(message)
Ejemplo n.º 5
0
    def element_text_should_be(self,
                               locator,
                               expected,
                               message=None,
                               ignore_case=False):
        """Verifies that element ``locator`` contains exact the text ``expected``.

        See the `Locating elements` section for details about the locator
        syntax.

        The ``message`` argument can be used to override the default error
        message.

        The ``ignore_case`` argument can be set to True to compare case
        insensitive, default is False.

        ``ignore_case`` argument is new in SeleniumLibrary 3.1.

        Use `Element Should Contain` if a substring match is desired.
        """
        self.info("Verifying element '%s' contains exact text '%s'." %
                  (locator, expected))
        text = before_text = self.find_element(locator).text
        if is_truthy(ignore_case):
            text = text.lower()
            expected = expected.lower()
        if text != expected:
            if is_noney(message):
                message = ("The text of element '%s' should have been '%s' "
                           "but it was '%s'." %
                           (locator, expected, before_text))
            raise AssertionError(message)
Ejemplo n.º 6
0
    def add_cookie(self,
                   name,
                   value,
                   path=None,
                   domain=None,
                   secure=None,
                   expiry=None):
        """Adds a cookie to your current session.

        ``name`` and ``value`` are required, ``path``, ``domain``, ``secure``
        and ``expiry`` are optional.  Expiry supports the same formats as
        the [http://robotframework.org/robotframework/latest/libraries/DateTime.html|DateTime]
        library or an epoch timestamp.

        Example:
        | `Add Cookie` | foo | bar |                            |
        | `Add Cookie` | foo | bar | domain=example.com         |
        | `Add Cookie` | foo | bar | expiry=2027-09-28 16:21:35 | # Expiry as timestamp.     |
        | `Add Cookie` | foo | bar | expiry=1822137695          | # Expiry as epoch seconds. |

        Prior to SeleniumLibrary 3.0 setting expiry did not work.
        """
        new_cookie = {'name': name, 'value': value}
        if not is_noney(path):
            new_cookie['path'] = path
        if not is_noney(domain):
            new_cookie['domain'] = domain
        # Secure must be True or False
        if not is_noney(secure):
            new_cookie['secure'] = is_truthy(secure)
        if not is_noney(expiry):
            new_cookie['expiry'] = self._expiry(expiry)
        self.driver.add_cookie(new_cookie)
Ejemplo n.º 7
0
 def create_safari(self, desired_capabilities, remote_url, options=None, service_log_path=None):
     if is_truthy(remote_url):
         defaul_caps = webdriver.DesiredCapabilities.SAFARI.copy()
         desired_capabilities = self._remote_capabilities_resolver(desired_capabilities, defaul_caps)
         return self._remote(desired_capabilities, remote_url)
     if options or service_log_path:
         logger.warn('Safari browser does not support Selenium options or service_log_path.')
     return webdriver.Safari(**desired_capabilities)
Ejemplo n.º 8
0
 def create_phantomjs(self, desired_capabilities, remote_url, options=None, service_log_path=None):
     warnings.warn('SeleniumLibrary support for PhantomJS has been deprecated, '
                   'please use headlesschrome or headlessfirefox instead.')
     if is_truthy(remote_url):
         defaul_caps = webdriver.DesiredCapabilities.PHANTOMJS.copy()
         desired_capabilities = self._remote_capabilities_resolver(desired_capabilities, defaul_caps)
         return self._remote(desired_capabilities, remote_url)
     if options:
         logger.warn('PhantomJS browser does not support Selenium options.')
     return webdriver.PhantomJS(service_log_path=service_log_path, **desired_capabilities)
Ejemplo n.º 9
0
    def press_keys(self, locator=None, *keys):
        """Simulates the user pressing key(s) to an element or on the active browser.


        If ``locator`` evaluates as false, see `Boolean arguments` for more
        details, then the ``keys`` are sent to the currently active browser.
        Otherwise element is searched and ``keys`` are send to the element
        identified by the ``locator``. In later case, keyword fails if element
        is not found. See the `Locating elements` section for details about
        the locator syntax.

        ``keys`` arguments can contain one or many strings, but it can not
        be empty. ``keys`` can also be a combination of
        [https://seleniumhq.github.io/selenium/docs/api/py/webdriver/selenium.webdriver.common.keys.html|Selenium Keys]
        and strings or a single Selenium Key. If Selenium Key is combined
        with strings, Selenium key and strings must be separated by the
        `+` character, like in `CONTROL+c`. Selenium Keys
        are space and case sensitive and Selenium Keys are not parsed
        inside of the string. Example AALTO, would send string `AALTO`
        and `ALT` not parsed inside of the string. But `A+ALT+O` would
        found Selenium ALT key from the ``keys`` argument. It also possible
        to press many Selenium Keys down at the same time, example
        'ALT+ARROW_DOWN`.

        If Selenium Keys are detected in the ``keys`` argument, keyword
        will press the Selenium Key down, send the strings and
         then release the Selenium Key. If keyword needs to send a Selenium
        Key as a string, then each character must be separated with
        `+` character, example `E+N+D`.

        `CTRL` is alias for
        [https://seleniumhq.github.io/selenium/docs/api/py/webdriver/selenium.webdriver.common.keys.html#selenium.webdriver.common.keys.Keys.CONTROL|Selenium CONTROL]
        and ESC is alias for
        [https://seleniumhq.github.io/selenium/docs/api/py/webdriver/selenium.webdriver.common.keys.html#selenium.webdriver.common.keys.Keys.ESCAPE|Selenium ESCAPE]

        New in SeleniumLibrary 3.3

        Examples:
        | `Press Keys` | text_field | AAAAA          |            | # Sends string "AAAAA" to element.                                                |
        | `Press Keys` | None       | BBBBB          |            | # Sends string "BBBBB" to currently active browser.                               |
        | `Press Keys` | text_field | E+N+D          |            | # Sends string "END" to element.                                                  |
        | `Press Keys` | text_field | XXX            | YY         | # Sends strings "XXX" and "YY" to element.                                        |
        | `Press Keys` | text_field | XXX+YY         |            | # Same as above.                                                                  |
        | `Press Keys` | text_field | ALT+ARROW_DOWN |            | # Pressing "ALT" key down, then pressing ARROW_DOWN and then releasing both keys. |
        | `Press Keys` | text_field | ALT            | ARROW_DOWN | # Pressing "ALT" key and then pressing ARROW_DOWN.                                |
        | `Press Keys` | text_field | CTRL+c         |            | # Pressing CTRL key down, sends string "c" and then releases CTRL key.            |
        | `Press Keys` | button     | RETURN         |            | # Pressing "ENTER" key to element.                                                |
        """
        parsed_keys = self._parse_keys(*keys)
        if is_truthy(locator):
            self.info('Sending key(s) %s to %s element.' % (keys, locator))
        else:
            self.info('Sending key(s) %s to page.' % str(keys))
        self._press_keys(locator, parsed_keys)
Ejemplo n.º 10
0
 def create_firefox(self, desired_capabilities, remote_url, ff_profile_dir, options=None, service_log_path=None):
     profile = self._get_ff_profile(ff_profile_dir)
     if is_truthy(remote_url):
         default_caps = webdriver.DesiredCapabilities.FIREFOX.copy()
         desired_capabilities = self._remote_capabilities_resolver(desired_capabilities, default_caps)
         return self._remote(desired_capabilities, remote_url,
                             profile, options)
     service_log_path = service_log_path if service_log_path else self._geckodriver_log
     if self._has_service_log_path(webdriver.Firefox):
         # service_log_path is supported from Selenium 3.14 onwards
         # If can be removed when minimum Selenium version is 3.14.0 or greater
         return webdriver.Firefox(options=options, firefox_profile=profile,
                                  service_log_path=service_log_path, **desired_capabilities)
     return webdriver.Firefox(options=options, firefox_profile=profile, **desired_capabilities)
Ejemplo n.º 11
0
    def click_element(self, locator, modifier=False, action_chain=False):
        """Click the element identified by ``locator``.

        See the `Locating elements` section for details about the locator
        syntax.

        The ``modifier`` argument can be used to pass
        [https://seleniumhq.github.io/selenium/docs/api/py/webdriver/selenium.webdriver.common.keys.html#selenium.webdriver.common.keys.Keys|Selenium Keys]
        when clicking the element. The `+` can be used as a separator
        for different Selenium Keys. The `CTRL` is internally translated to
        the `CONTROL` key. The ``modifier`` is space and case insensitive, example
        "alt" and " aLt " are supported formats to
        [https://seleniumhq.github.io/selenium/docs/api/py/webdriver/selenium.webdriver.common.keys.html#selenium.webdriver.common.keys.Keys.ALT|ALT key]
        . If ``modifier`` does not match to Selenium Keys, keyword fails.

        If ``action_chain`` argument is true, see `Boolean arguments` for more
        details on how to set boolean argument, then keyword uses ActionChain
        based click instead of the <web_element>.click() function. If both
        ``action_chain`` and ``modifier`` are defined, the click will be
        performed using ``modifier`` and ``action_chain`` will be ignored.

        Example:
        | Click Element | id:button |                   | # Would click element without any modifiers.               |
        | Click Element | id:button | CTRL              | # Would click element with CTLR key pressed down.          |
        | Click Element | id:button | CTRL+ALT          | # Would click element with CTLR and ALT keys pressed down. |
        | Click Element | id:button | action_chain=True | # Clicks the button using an Selenium  ActionChains        |

        The ``modifier`` argument is new in SeleniumLibrary 3.2
        The ``action_chain`` argument is new in SeleniumLibrary 4.1
        """
        if is_truthy(modifier):
            self._click_with_modifier(locator, [None, None], modifier)
        elif is_truthy(action_chain):
            self._click_with_action_chain(locator)
        else:
            self.info("Clicking element '%s'." % locator)
            self.find_element(locator).click()
Ejemplo n.º 12
0
 def create_edge(self, desired_capabilities, remote_url, options=None, service_log_path=None):
     if is_truthy(remote_url):
         defaul_caps = webdriver.DesiredCapabilities.EDGE.copy()
         desired_capabilities = self._remote_capabilities_resolver(desired_capabilities, defaul_caps)
         return self._remote(desired_capabilities, remote_url)
     if self._has_options(webdriver.Edge) and self._has_service_log_path(webdriver.Edge):
         # options is supported from Selenium 4.0 onwards
         # If can be removed when minimum Selenium version is 4.0 or greater
         return webdriver.Edge(options=options, service_log_path=service_log_path, **desired_capabilities)
     if not self._has_options(webdriver.Edge) and self._has_service_log_path(webdriver.Edge):
         # service_log_path is supported from Selenium 3.14 onwards
         # If can be removed when minimum Selenium version is 3.14.0 or greater
         logger.warn('This version of Selenium does not support options argument.')
         return webdriver.Edge(service_log_path=service_log_path, **desired_capabilities)
     logger.warn('This version of Selenium does not support options or service_log_path argument.')
     return webdriver.Edge(**desired_capabilities)
Ejemplo n.º 13
0
 def _press_keys(self, locator, parsed_keys):
     if is_truthy(locator):
         element = self.find_element(locator)
     else:
         element = None
     for parsed_key in parsed_keys:
         actions = ActionChains(self.driver)
         special_keys = []
         for key in parsed_key:
             if self._selenium_keys_has_attr(key.original):
                 special_keys = self._press_keys_special_keys(
                     actions, element, parsed_key, key, special_keys)
             else:
                 self._press_keys_normal_keys(actions, element, key)
         for special_key in special_keys:
             self.info('Releasing special key %s.' % special_key.original)
             actions.key_up(special_key.converted)
         actions.perform()
Ejemplo n.º 14
0
    def get_list_items(self, locator, values=False):
        """Returns all labels or values of selection list ``locator``.

        See the `Locating elements` section for details about the locator
        syntax.

        Returns visible labels by default, but values can be returned by
        setting the ``values`` argument to a true value (see `Boolean
        arguments`).

        Example:
        | ${labels} = | `Get List Items` | mylist              |             |
        | ${values} = | `Get List Items` | css:#example select | values=True |

        Support to return values is new in SeleniumLibrary 3.0.
        """
        options = self._get_options(locator)
        if is_truthy(values):
            return self._get_values(options)
        else:
            return self._get_labels(options)
Ejemplo n.º 15
0
    def get_window_size(self, inner=False):
        """Returns current window width and height as integers.

        See also `Set Window Size`.

        If ``inner`` parameter is set to True, keyword returns
        HTML DOM window.innerWidth and window.innerHeight properties.
        See `Boolean arguments` for more details on how to set boolean
        arguments. The ``inner`` is new in SeleniumLibrary 4.0.

        Example:
        | ${width} | ${height}= | `Get Window Size` |      |
        | ${width} | ${height}= | `Get Window Size` | True |
        """
        if is_truthy(inner):
            inner_width = int(
                self.driver.execute_script("return window.innerWidth;"))
            inner_height = int(
                self.driver.execute_script("return window.innerHeight;"))
            return inner_width, inner_height
        size = self.driver.get_window_size()
        return size['width'], size['height']
Ejemplo n.º 16
0
    def __init__(self,
                 timeout=5.0,
                 implicit_wait=0.0,
                 run_on_failure='Capture Page Screenshot',
                 screenshot_root_directory=None,
                 plugins=None,
                 event_firing_webdriver=None):
        """SeleniumLibrary can be imported with several optional arguments.

        - ``timeout``:
          Default value for `timeouts` used with ``Wait ...`` keywords.
        - ``implicit_wait``:
          Default value for `implicit wait` used when locating elements.
        - ``run_on_failure``:
          Default action for the `run-on-failure functionality`.
        - ``screenshot_root_directory``:
          Location where possible screenshots are created. If not given,
          the directory where the log file is written is used.
        - ``plugins``:
          Allows extending the SeleniumLibrary with external Python classes.
        - ``event_firing_webdriver``:
          Class for wrapping Selenium with
          [https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.event_firing_webdriver.html#module-selenium.webdriver.support.event_firing_webdriver|EventFiringWebDriver]
        """
        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
        self._element_finder = ElementFinder(self)
        self._plugin_keywords = []
        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)
        ]
        self.ROBOT_LIBRARY_LISTENER = LibraryListener()
        self._running_keyword = None
        self.event_firing_webdriver = None
        if is_truthy(event_firing_webdriver):
            self.event_firing_webdriver = self._parse_listener(
                event_firing_webdriver)
        self._plugins = []
        if is_truthy(plugins):
            plugin_libs = self._parse_plugins(plugins)
            self._plugins = plugin_libs
            libraries = libraries + plugin_libs
        self._drivers = WebDriverCache()
        DynamicCore.__init__(self, libraries)
Ejemplo n.º 17
0
 def _input_text_into_text_field(self, locator, text, clear):
     element = self.find_element(locator)
     if is_truthy(clear):
         element.clear()
     element.send_keys(text)
Ejemplo n.º 18
0
    def open_browser(self,
                     url=None,
                     browser='firefox',
                     alias=None,
                     remote_url=False,
                     desired_capabilities=None,
                     ff_profile_dir=None,
                     options=None,
                     service_log_path=None,
                     devType=None):
        """Opens a new browser instance to the optional ``url``.

        The ``browser`` argument specifies which browser to use. The
        supported browsers are listed in the table below. The browser names
        are case-insensitive and some browsers have multiple supported names.

        |    = Browser =    |        = Name(s) =       |
        | Firefox           | firefox, ff              |
        | Google Chrome     | googlechrome, chrome, gc |
        | Headless Firefox  | headlessfirefox          |
        | Headless Chrome   | headlesschrome           |
        | Internet Explorer | internetexplorer, ie     |
        | Edge              | edge                     |
        | Safari            | safari                   |
        | Opera             | opera                    |
        | Android           | android                  |
        | Iphone            | iphone                   |
        | PhantomJS         | phantomjs                |
        | HTMLUnit          | htmlunit                 |
        | HTMLUnit with Javascript | htmlunitwithjs    |

        To be able to actually use one of these browsers, you need to have
        a matching Selenium browser driver available. See the
        [https://github.com/robotframework/SeleniumLibrary#browser-drivers|
        project documentation] for more details. Headless Firefox and
        Headless Chrome are new additions in SeleniumLibrary 3.1.0
        and require Selenium 3.8.0 or newer.

        After opening the browser, it is possible to use optional 
        ``url`` to navigate the browser to the desired address.

        Optional ``alias`` is an alias given for this browser instance and
        it can be used for switching between browsers. When same ``alias``
        is given with two `Open Browser` keywords, the first keyword will
        open a new browser, but the second one will switch to the already
        opened browser and will not open a new browser. The ``alias``
        definition overrules ``browser`` definition. When same ``alias``
        is used but a different ``browser`` is defined, then switch to
        a browser with same alias is done and new browser is not opened.
        An alternative approach for switching is using an index returned
        by this keyword. These indices start from 1, are incremented when new
        browsers are opened, and reset back to 1 when `Close All Browsers`
        is called. See `Switch Browser` for more information and examples.

        Optional ``remote_url`` is the URL for a
        [https://github.com/SeleniumHQ/selenium/wiki/Grid2|Selenium Grid].

        Optional ``desired_capabilities`` can be used to configure, for example,
        logging preferences for a browser or a browser and operating system
        when using [http://saucelabs.com|Sauce Labs]. Desired capabilities can
        be given either as a Python dictionary or as a string in the format
        ``key1:value1,key2:value2``.
        [https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities|
        Selenium documentation] lists possible capabilities that can be
        enabled.

        Optional ``ff_profile_dir`` is the path to the Firefox profile
        directory if you wish to overwrite the default profile Selenium
        uses. Notice that prior to SeleniumLibrary 3.0, the library
        contained its own profile that was used by default. The
        ``ff_profile_dir`` can also be an instance of the
        [https://seleniumhq.github.io/selenium/docs/api/py/webdriver_firefox/selenium.webdriver.firefox.firefox_profile.html|selenium.webdriver.FirefoxProfile]
        . As a third option, it is possible to use `FirefoxProfile` methods
        and attributes to define the profile using methods and attributes
        in the same way as with ``options`` argument. Example: It is possible
        to use FirefoxProfile `set_preference` to define different
        profile settings.

        Optional ``options`` argument allows defining browser specific
        Selenium options. Example for Chrome, the ``options`` argument
        allows defining the following
        [https://seleniumhq.github.io/selenium/docs/api/py/webdriver_chrome/selenium.webdriver.chrome.options.html#selenium.webdriver.chrome.options.Options|methods and attributes]
        and for Firefox these
        [https://seleniumhq.github.io/selenium/docs/api/py/webdriver_firefox/selenium.webdriver.firefox.options.html?highlight=firefox#selenium.webdriver.firefox.options.Options|methods and attributes]
        are available. Please note that not all browsers, supported by the
        SeleniumLibrary, have Selenium options available. Therefore please
        consult the Selenium documentation which browsers do support
        the Selenium options. If ``browser`` argument is `android` then
        [https://seleniumhq.github.io/selenium/docs/api/py/webdriver_chrome/selenium.webdriver.chrome.options.html#selenium.webdriver.chrome.options.Options|Chrome options]
        is used. Selenium options are also supported, when ``remote_url``
        argument is used.

        The SeleniumLibrary ``options`` argument accepts Selenium
        options in two different formats: as a string and as Python object
        which is an instance of the Selenium options class.

        The string format allows defining Selenium options methods
        or attributes and their arguments in Robot Framework test product.
        The method and attributes names are case and space sensitive and
        must match to the Selenium options methods and attributes names.
        When defining a method, it must be defined in a similar way as in
        python: method name, opening parenthesis, zero to many arguments
        and closing parenthesis. If there is a need to define multiple
        arguments for a single method, arguments must be separated with
        comma, just like in Python. Example: `add_argument("--headless")`
        or `add_experimental_option("key", "value")`. Attributes are
        defined in a similar way as in Python: attribute name, equal sign,
        and attribute value. Example, `headless=True`. Multiple methods
        and attributes must be separated by a semicolon. Example:
        `add_argument("--headless");add_argument("--start-maximized")`.

        Arguments allow defining Python product types and arguments are
        evaluated by using Python
        [https://docs.python.org/3/library/ast.html#ast.literal_eval|ast.literal_eval].
        Strings must be quoted with single or double quotes, example "value"
        or 'value'. It is also possible to define other Python builtin
        product types, example `True` or `None`, by not using quotes
        around the arguments.

        The string format is space friendly. Usually, spaces do not alter
        the defining methods or attributes. There are two exceptions.
        In some Robot Framework test product formats, two or more spaces are
        considered as cell separator and instead of defining a single
        argument, two or more arguments may be defined. Spaces in string
        arguments are not removed and are left as is. Example
        `add_argument ( "--headless" )` is same as
        `add_argument("--headless")`. But `add_argument(" --headless ")` is
        not same same as `add_argument ( "--headless" )`, because
        spaces inside of quotes are not removed.

        As last format, ``options`` argument also supports receiving
        the Selenium options as Python class instance. In this case, the
        instance is used as-is and the SeleniumLibrary will not convert
        the instance to other formats.
        For example, if the following code return value is saved to
        `${options}` variable in the Robot Framework product:
        | options = webdriver.ChromeOptions()
        | options.add_argument('--disable-dev-shm-usage')
        | return options

        Then the `${options}` variable can be used as an argument to
        ``options``.

        Example the ``options`` argument can be used to launch Chomium-based
        applications which utilize the 
        [https://bitbucket.org/chromiumembedded/cef/wiki/UsingChromeDriver|Chromium Embedded Framework]
        . To lauch Chomium-based application, use ``options`` to define
        `binary_location` attribute and use `add_argument` method to define
        `remote-debugging-port` port for the application. Once the browser
        is opened, the test can interact with the embedded web-content of
        the system under test.

        Optional ``service_log_path`` argument defines the name of the
        file where to write the browser driver logs. If the
        ``service_log_path``  argument contain a  marker ``{index}``, it
        will be automatically replaced with unique running
        index preventing files to be overwritten. Indices start's from 1,
        and how they are represented can be customized using Python's
        [https://docs.python.org/3/library/string.html#format-string-syntax|
        format string syntax].

        Examples:
        | `Open Browser` | http://example.com | Chrome  |                                         |
        | `Open Browser` | http://example.com | Firefox | alias=Firefox                           |
        | `Open Browser` | http://example.com | Edge    | remote_url=http://127.0.0.1:4444/wd/hub |
        | `Open Browser` | about:blank        |         |                                         |
        | `Open Browser` | browser=Chrome     |         |                                         |

        Alias examples:
        | ${1_index} =    | `Open Browser` | http://example.com | Chrome  | alias=Chrome     | # Opens new browser because alias is new.         |
        | ${2_index} =    | `Open Browser` | http://example.com | Firefox |                  | # Opens new browser because alias is not defined. |
        | ${3_index} =    | `Open Browser` | http://example.com | Chrome  | alias=Chrome     | # Switches to the browser with Chrome alias.      |
        | ${4_index} =    | `Open Browser` | http://example.com | Chrome  | alias=${1_index} | # Switches to the browser with Chrome alias.      |
        | Should Be Equal | ${1_index}     | ${3_index}         |         |                  |                                                   |
        | Should Be Equal | ${1_index}     | ${4_index}         |         |                  |                                                   |
        | Should Be Equal | ${2_index}     | ${2}               |         |                  |                                                   |

        Example when using
        [https://seleniumhq.github.io/selenium/docs/api/py/webdriver_chrome/selenium.webdriver.chrome.options.html#selenium.webdriver.chrome.options.Options|Chrome options]
        method:
        | `Open Browser` | http://example.com | Chrome | options=add_argument("--disable-popup-blocking"); add_argument("--ignore-certificate-errors") | # Sting format                    |
        |  ${options} =  |     Get Options    |        |                                                                                               | # Selenium options instance       |
        | `Open Browser` | http://example.com | Chrome | options=${options}                                                                            |                                   |
        | `Open Browser` | None               | Chrome | options=binary_location="/path/to/binary";add_argument("remote-debugging-port=port")          | # Start Chomium-based application |

        Example for FirefoxProfile
        | `Open Browser` | http://example.com | Firefox | ff_profile_dir=/path/to/profile                                                  | # Using profile from disk                       |
        | `Open Browser` | http://example.com | Firefox | ff_profile_dir=${FirefoxProfile_instance}                                        | # Using instance of FirefoxProfile              |
        | `Open Browser` | http://example.com | Firefox | ff_profile_dir=set_preference("key", "value");set_preference("other", "setting") | # Defining profile using FirefoxProfile mehtods |

        If the provided configuration options are not enough, it is possible
        to use `Create Webdriver` to customize browser initialization even
        more.

        Applying ``desired_capabilities`` argument also for local browser is
        new in SeleniumLibrary 3.1.

        Using ``alias`` to decide, is the new browser opened is new
        in SeleniumLibrary 4.0. The ``options`` and ``service_log_path``
        are new in SeleniumLibrary 4.0. Support for ``ff_profile_dir``
        accepting an instance of the `selenium.webdriver.FirefoxProfile`
        and support defining FirefoxProfile with methods and
        attributes are new in SeleniumLibrary 4.0.
        
        Making ``url`` optional is new in SeleniumLibrary 4.1.
        """

        index = self.drivers.get_index(alias)

        if index:
            self.info('Using existing browser from index %s.' % index)
            self.switch_browser(alias)
            if is_truthy(url):
                self.go_to(url)

            return index

        return self._make_new_browser(url, browser, alias, remote_url,
                                      desired_capabilities, ff_profile_dir,
                                      options, service_log_path, devType)
Ejemplo n.º 19
0
 def create_opera(self, desired_capabilities, remote_url, options=None, service_log_path=None):
     if is_truthy(remote_url):
         defaul_caps = webdriver.DesiredCapabilities.OPERA.copy()
         desired_capabilities = self._remote_capabilities_resolver(desired_capabilities, defaul_caps)
         return self._remote(desired_capabilities, remote_url, options=options)
     return webdriver.Opera(options=options, service_log_path=service_log_path, **desired_capabilities)