Beispiel #1
0
def test_prefs_to_dict():
    expected_result = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
    assert prefs_to_dict(
        '"key1":"value1", "key2":"value2", "key3":"value3"') == expected_result
    assert prefs_to_dict(
        'key1: value1, key2:value2, key3:value3') == expected_result
    assert prefs_to_dict(expected_result) == expected_result
Beispiel #2
0
def open_browser(profile_dir=None,
                 capabilities=None,
                 proxy=None,
                 headless=False,
                 binary=None,
                 executable_path="geckodriver",
                 firefox_args=None,
                 timeout=30,
                 log_path="geckodriver.log",
                 **kwargs):
    """Open Firefox browser and cache the driver.

    Parameters
    ----------
    binary : FirefoxBinary or str
        If string then is needs to be the absolute path to the binary. If
        undefined, the system default Firefox installation will be used.
    timeout : int
        Time to wait for Firefox to launch when using the extension connection.
    capabilities : dict
        Dictionary of desired capabilities.
    executable_path : str (Default geckodriver)
        Full path to override which geckodriver binary to use for Firefox
        47.0.1 and greater, which defaults to picking up the binary from the
        system path.
    log_path : str (Default "geckdriver.log")
        Where to log information from the driver.
    firefox_args : list
        Optional arguments to modify browser settings.
        https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options
    """
    options = Options()
    if headless:
        logger.warn('Deprecated.\n'
                    'Headless mode can be activated just like any other firefox option:\n'
                    '"OpenBrowser   https://qentinel.com    ${BROWSER}   -headless"')
        options.add_argument('-headless')
        CONFIG.set_value("Headless", True)
    if profile_dir:
        logger.warn('Deprecated.\n'
                    'Profile directory can be selected like any other firefox option:\n'
                    '"OpenBrowser   https://qentinel.com   ${BROWSER}  -profile /path/to/profile"')
        options.add_argument('-profile {}'.format(profile_dir))
    options.set_preference("browser.helperApps.neverAsk.saveToDisk", browser.MIME_TYPES)
    options.set_preference("extensions.update.enabled", False)
    options.set_preference("app.update.enabled", False)
    options.set_preference("app.update.auto", False)
    options.set_preference("dom.webnotifications.enabled", False)
    options.set_preference("privacy.socialtracking.block_cookies.enabled", False)
    kwargs = {k.lower(): v for k, v in kwargs.items()}  # Kwargs keys to lowercase
    if 'prefs' in kwargs:
        if isinstance(kwargs.get('prefs'), dict):
            prefs = kwargs.get('prefs')
        else:
            prefs = util.prefs_to_dict(kwargs.get('prefs').strip())
        for item in prefs.items():
            key, value = item[0], item[1]
            logger.info('Using prefs: {} = {}'.format(key, value), also_console=True)
            if not isinstance(value, int) and value.isdigit():
                value = int(value)
            options.set_preference(key, value)
    if firefox_args:
        if any('headless' in _.lower() for _ in firefox_args):
            CONFIG.set_value("Headless", True)
        for option in firefox_args:
            option = option.strip()
            options.add_argument(option)
    driver = webdriver.Firefox(executable_path=executable_path, proxy=proxy, firefox_binary=binary,
                               desired_capabilities=capabilities, options=options, timeout=timeout,
                               log_path=log_path)
    if os.name == 'nt':  # Maximize window if running on windows, doesn't work on linux
        driver.maximize_window()
    browser.cache_browser(driver)
    return driver
Beispiel #3
0
def open_browser(executable_path="chromedriver",
                 chrome_args=None,
                 desired_capabilities=None,
                 **kwargs):
    """Open Chrome browser instance and cache the driver.

    Parameters
    ----------
    executable_path : str (Default "chromedriver")
        path to the executable. If the default is used it assumes the
        executable is in the $PATH.
    port : int (Default 0)
        port you would like the service to run, if left as 0, a free port will
        be found.
    desired_capabilities : dict (Default None)
        Dictionary object with non-browser specific capabilities only, such as
        "proxy" or "loggingPref".
    chrome_args : Optional arguments to modify browser settings
    """
    options = Options()
    logger.debug('opt: {}'.format(options))

    # If user wants to re-use existing browser session then
    # he/she has to set variable BROWSER_REUSE_ENABLED to True.
    # If enabled, then web driver connection details are written
    # to an argument file. This file enables re-use of the current
    # chrome session.
    #
    # When variables BROWSER_SESSION_ID and BROWSER_EXECUTOR_URL are
    # set from argument file, then OpenBrowser will use those
    # parameters instead of opening new chrome session.
    # New Remote Web Driver is created in headless mode.
    chrome_path = kwargs.get(
        'chrome_path', None) or BuiltIn().get_variable_value('${CHROME_PATH}')
    if chrome_path:
        options.binary_location = chrome_path
    browser_reuse, session_id, executor_url = check_browser_reuse(**kwargs)
    logger.debug('browser_reuse: {}, session_id: {}, executor_url:  {}'.format(
        browser_reuse, session_id, executor_url))
    if browser_reuse and session_id and executor_url:
        options.add_argument("headless")

        # Gets rid of Devtools listening .... printing
        options.add_experimental_option('excludeSwitches', ['enable-logging'])

        driver = Remote(command_executor=executor_url,
                        desired_capabilities=options.to_capabilities())
        BuiltIn().set_global_variable('${BROWSER_REMOTE_SESSION_ID}',
                                      driver.session_id)
        driver.session_id = session_id
    else:
        if user.is_root():
            options.add_argument("no-sandbox")
        if chrome_args:
            if any('headless' in _.lower() for _ in chrome_args):
                CONFIG.set_value('Headless', True)
            for item in chrome_args:
                options.add_argument(item.lstrip())
        # options.add_argument("start-maximized")
        options.add_argument("--disable-notifications")
        if 'headless' in kwargs:
            CONFIG.set_value('Headless', True)
            options.add_argument("headless")
        if 'prefs' in kwargs:
            if isinstance(kwargs.get('prefs'), dict):
                prefs = kwargs.get('prefs')
            else:
                prefs = util.prefs_to_dict(kwargs.get('prefs').strip())
            options.add_experimental_option('prefs', prefs)

        driver = Chrome(BuiltIn().get_variable_value('${CHROMEDRIVER_PATH}')
                        or executable_path,
                        options=options,
                        desired_capabilities=desired_capabilities)

        browser_reuse_enabled = util.par2bool(
            BuiltIn().get_variable_value('${BROWSER_REUSE_ENABLED}')) or False
        if browser_reuse_enabled:
            # Write WebDriver session info to RF arguments file for re-use
            write_browser_session_argsfile(driver.session_id,
                                           driver.command_executor._url)  # pylint: disable=protected-access

            # Clear possible existing global values
            BuiltIn().set_global_variable('${BROWSER_SESSION_ID}', None)
            BuiltIn().set_global_variable('${BROWSER_EXECUTOR_URL}', None)

    browser.cache_browser(driver)
    return driver
Beispiel #4
0
def open_browser(executable_path="msedgedriver",
                 edge_args=None,
                 desired_capabilities=None,
                 **kwargs):
    """Open Edge browser instance and cache the driver.

    Parameters
    ----------
    executable_path : str (Default "msedgedriver")
        path to the executable. If the default is used it assumes the
        executable is in the $PATH.
    port : int (Default 0)
        port you would like the service to run, if left as 0, a free port will
        be found.
    desired_capabilities : dict (Default None)
        Dictionary object with non-browser specific capabilities only, such as
        "proxy" or "loggingPref".
    chrome_args : Optional arguments to modify browser settings
    """
    options = Options()
    options.use_chromium = True

    # Gets rid of Devtools listening .... printing
    # other non-sensical error messages
    options.add_experimental_option('excludeSwitches', ['enable-logging'])

    if platform.system().lower() == "windows":
        options.set_capability("platform", "WINDOWS")

    if platform.system().lower() == "linux":
        options.set_capability("platform", "LINUX")

    if platform.system().lower() == "darwin":
        options.set_capability("platform", "MAC")

    # If user wants to re-use existing browser session then
    # he/she has to set variable BROWSER_REUSE_ENABLED to True.
    # If enabled, then web driver connection details are written
    # to an argument file. This file enables re-use of the current
    # chrome session.
    #
    # When variables BROWSER_SESSION_ID and BROWSER_EXECUTOR_URL are
    # set from argument file, then OpenBrowser will use those
    # parameters instead of opening new chrome session.
    # New Remote Web Driver is created in headless mode.
    edge_path = kwargs.get(
        'edge_path', None) or BuiltIn().get_variable_value('${EDGE_PATH}')
    if edge_path:
        options.binary_location = edge_path

    if user.is_root() or user.is_docker():
        options.add_argument("no-sandbox")
    if edge_args:
        if any('--headless' in _.lower() for _ in edge_args):
            CONFIG.set_value('Headless', True)
        for item in edge_args:
            options.add_argument(item.lstrip())
    options.add_argument("start-maximized")
    options.add_argument("--disable-notifications")
    if 'headless' in kwargs:
        CONFIG.set_value('Headless', True)
        options.add_argument("--headless")
    if 'prefs' in kwargs:
        if isinstance(kwargs.get('prefs'), dict):
            prefs = kwargs.get('prefs')
        else:
            prefs = util.prefs_to_dict(kwargs.get('prefs').strip())
        options.add_experimental_option('prefs', prefs)
        logger.warn("prefs: {}".format(prefs))
    driver = Edge(BuiltIn().get_variable_value('${EDGEDRIVER_PATH}')
                  or executable_path,
                  options=options,
                  capabilities=desired_capabilities)
    browser.cache_browser(driver)
    return driver