Exemplo n.º 1
0
def get_element_by_locator_text(locator, anchor="1", index=1, **kwargs):
    """Find element by it's visible text.

    Accepted kwargs:
        parent(tagName):Can be used when target element is some of the locators parent.
        child(tagName): Find clickable target from locator's child elements.
        allow_non_existent = True: Function returns immediately if element is not found
        css=False: Use this to bypass css search when finding elements by visible text
    """
    index = int(index) - 1
    try:
        web_element = get_text_using_anchor(locator, anchor, **kwargs)
    except (QWebElementNotFoundError, InvalidSelectorException,
            JavascriptException, WebDriverException):
        try:
            web_element = element.get_unique_element_by_xpath(locator)
        except (QWebElementNotFoundError, InvalidSelectorException,
                NoSuchFrameException) as e:
            no_raise = util.par2bool(kwargs.get('allow_non_existent', False))
            if no_raise:
                return None
            raise QWebElementNotFoundError(e)  # pylint: disable=W0707
    if web_element:
        if 'parent' in kwargs and kwargs['parent']:
            tag_name = kwargs['parent']
            web_element = element.get_parent_element(web_element, tag_name)
        elif 'child' in kwargs and kwargs['child']:
            tag_name = kwargs['child']
            web_element = element.get_element_from_childnodes(
                web_element, tag_name, dom_traversing=False)[index]
        if CONFIG['SearchMode']:
            element.draw_borders(web_element)
        return web_element
    raise QWebElementNotFoundError('Element not found')
Exemplo n.º 2
0
 def _get_row_by_locator_text(rows, locator, anchor):
     matches = []
     input_elements = []
     row_index = []
     anchor_text = None
     try:
         anchor = int(anchor) - 1
     except ValueError:
         anchor_text = anchor
     for index, row in enumerate(rows):
         row_content = row.text
         if locator == 'EMPTY' and row_content.strip() == '':
             return row, index
         input_elements = javascript.execute_javascript(
             'return arguments[0].querySelectorAll("input, textarea")', row)
         for elem in input_elements:
             row_content += str(
                 javascript.execute_javascript('return arguments[0].value',
                                               elem))
         if locator in row_content:
             if anchor_text and anchor_text in row_content:
                 return row, index
             row_index.append(index)
             matches.append(row)
     if matches and not anchor_text:
         return matches[anchor], row_index[anchor]
     raise QWebElementNotFoundError(
         'Row that includes texts {} and {} not found'.format(
             locator, anchor_text))
Exemplo n.º 3
0
def get_elements_by_attributes(css, locator=None, **kwargs):
    any_element = util.par2bool(kwargs.get('any_element', None))
    partial = util.par2bool(kwargs.get('partial_match',
                                       CONFIG['PartialMatch']))
    if 'tag' in kwargs:
        css = kwargs.get('tag')
    try:
        elements = javascript.get_all_elements(css)
        if any_element:
            return elements
        matches = javascript.get_by_attributes(elements,
                                               locator.replace("\'", "\\'"),
                                               partial)
        logger.debug(
            'attrfunc found full matches: {}, partial matches: {}'.format(
                matches.get('full'), matches.get('partial')))
        full, partial = matches.get('full'), matches.get('partial')
    except (WebDriverException, JavascriptException, AttributeError) as e:
        logger.debug(
            'Got exception from get elements by attributes: {}'.format(e))
        full, partial = [], []
    if 'element_kw' not in kwargs:
        return full, partial
    web_elements = full + partial
    if web_elements:
        if CONFIG['SearchMode']:
            draw_borders(web_elements)
        return web_elements
    raise QWebElementNotFoundError(
        'Element with {} attribute not found'.format(locator))
Exemplo n.º 4
0
def get_dd_elements_from_all_documents(locator, anchor, index, **kwargs):
    if int(index) > 0:
        index = int(index) - 1
    css_selector = CONFIG["CssSelectors"]
    if not css_selector or locator.startswith('xpath=') or locator.startswith(
            '//'):
        select = get_dropdown_element_by_locator(locator, anchor)
    elif Table.is_table_coordinates(locator):
        table = Table.ACTIVE_TABLE.update_table()
        if table is None:
            raise QWebInstanceDoesNotExistError(
                'Table has not been defined with UseTable keyword')
        locator = table.get_table_cell(locator, anchor)
        select = element.get_element_from_childnodes(
            locator, 'select', dom_traversing=False)[index]
    else:
        select = get_dropdown_element_by_css_selector(locator, anchor, index,
                                                      **kwargs)
    if not select:
        select = get_dropdown_element_by_locator(locator, anchor)
    if select:
        if CONFIG['SearchMode']:
            element.draw_borders(select)
        return Select(select)
    raise QWebElementNotFoundError('No matching elements found')
Exemplo n.º 5
0
def click_icon(image, template_res_w=1920, browser_res_w=1920, timeout=0):  # pylint: disable=unused-argument
    """Click the icon on the screen.

    In case you want to click icons you always have to have reference images.

    If reference picture are not in default folders (images, files, downloads) then
    BASE_IMAGE_PATH should be defined in a robot file before using this keyword

    Examples
    --------
    .. code-block:: robotframework

        *** Variables ***
        ${BASE_IMAGE_PATH}          ${CURDIR}${/}..${/}resources${/}images

    BASE_IMAGE_PATH should lead to the folder where all your reference icons are

    .. code-block:: robotframework

        ClickIcon                   plane

    """
    template_res_w, browser_res_w = int(template_res_w), int(browser_res_w)
    image_path = icon.get_full_image_path(image)
    x, y = icon.image_recognition(image_path,
                                  template_res_w,
                                  browser_res_w,
                                  pyautog=True)
    if x == -1:
        raise QWebElementNotFoundError(
            "Couldn't find the icon from the screen")
    pyautogui.moveTo(x, y)
    pyautogui.click()
Exemplo n.º 6
0
def get_unique_element_by_xpath(xpath, **kwargs):
    """Get element if it is needed to be unique.

    One use case is that when xpath is written in the test script with
    the prefix xpath=.

    Parameters
    ----------
    xpath : str
        XPath string. If 'xpath=' -prefix is used, it will be omitted.
    """
    if xpath.startswith("xpath="):
        xpath = xpath.split("=", 1)[1]
    elements = get_webelements_in_active_area(xpath, **kwargs)
    # pylint: disable=no-else-return
    if elements and len(elements) == 1:
        if CONFIG['SearchMode']:
            draw_borders(elements[0])
        return elements[0]
    elif not elements:
        raise QWebElementNotFoundError(
            'XPath {} did not find any elements'.format(xpath))
    raise QWebValueError(
        'XPath {} matched {} elements. Needs to be unique'.format(
            xpath, len(elements)))
Exemplo n.º 7
0
def get_element_count(locator, timeout=0, **kwargs):  # pylint: disable=unused-argument
    r"""Get count of appearances for certain web element.

    Keyword waits until timeout has passed. If timeout is not specified, it
    uses default timeout that can be adjusted with DefaultTimeout keyword.

    GetTextCount does not require for the text to be unique.

    Examples
    --------
    .. code-block:: robotframework

        ${COUNT}    GetElementCount       //*[@id\="Foo"]
        ${COUNT}    GetElementCount       Foo    tag=div

    Parameters
    ----------
    locator : str
        Xpath or some attribute value of element. When using XPaths, the equal sign "=" must be
        escaped with a "\".
    timeout : str | int
        How long we try to find text before failing. Default 10 (seconds)
    Accepted kwargs:
        tag=tagname: Needed when attribute value is used as a locator
    """
    kwargs['element_kw'] = True
    if 'tag' in kwargs:
        web_elements = element.get_elements_by_attributes(
            kwargs.get('tag'), locator, **kwargs)
    else:
        web_elements = element.get_webelements(locator, **kwargs)
    if web_elements:
        return len(web_elements)
    raise QWebElementNotFoundError('Webelements not found')
Exemplo n.º 8
0
def find_text(text):
    try:
        if javascript.execute_javascript(
                "return window.find('{}')".format(text.replace("\'", "\\'"))):
            return True
    except WebDriverException as e:
        logger.debug('Got webdriver exception from find text func: {}'.format(e))
    raise QWebElementNotFoundError('Text not found')
Exemplo n.º 9
0
def get_parent_list_element(locator_element, css):
    try:
        web_element = javascript.get_parent_list(locator_element, css)
    except (WebDriverException, JavascriptException) as e:
        web_element = None
        logger.debug('Got Exception from get_parent_list: {}'.format(e))
    if web_element:
        return web_element
    raise QWebElementNotFoundError('Parent with tag {} not found.'.format(css))
Exemplo n.º 10
0
 def get_table_by_locator_table(locator, parent, child, level, index):
     if parent:
         script = ".parentElement.closest('table')" * int(level)
         parent_table = javascript.execute_javascript(
             "return arguments[0]{}".format(script), locator)
         if parent_table:
             if not child:
                 return parent_table
             locator = parent_table
         else:
             raise QWebElementNotFoundError('No parent table found')
     if child:
         script = ".querySelectorAll('table')[{}]".format(int(index) - 1)
         child_table = javascript.execute_javascript(
             "return arguments[0]{}".format(script), locator)
         if child_table:
             return child_table
         raise QWebElementNotFoundError('No child table found')
     raise QWebElementNotFoundError('Sub/parent table not found')
Exemplo n.º 11
0
def get_checkbox_elements_from_all_documents(locator, anchor, index, **kwargs):
    """Function for finding checkbox elements.
    Parameters
    ----------
    locator : str
        Label text or attribute that points to the checkbox.
    anchor : str
        in case there is duplicates.
    index : int
        If multiple matches. Use index to pick correct one.
    Returns
    -------
    WebElement
    """
    index = int(index) - 1
    css_selector = CONFIG["CssSelectors"]
    css = '[type="checkbox"], [role="checkbox"]'
    if Table.is_table_coordinates(locator):
        table = Table.ACTIVE_TABLE.update_table()
        if table is None:
            raise QWebInstanceDoesNotExistError(
                'Table has not been defined with UseTable keyword')
        locator_element = table.get_table_cell(locator, anchor)
        checkbox_element = element.get_element_from_childnodes(
            locator_element, css, dom_traversing=False, **kwargs)
        if checkbox_element:
            return checkbox_element[index], locator_element
        raise QWebElementNotFoundError('No matching checkbox found')
    if not css_selector or locator.startswith('xpath=') or locator.startswith(
            '//'):
        checkbox_element, locator_element = get_checkbox_by_locator(
            locator, anchor=anchor)
    else:
        checkbox_element, locator_element = get_checkbox_by_css_selector(
            locator, anchor=anchor, index=index, **kwargs)
        if not checkbox_element:
            checkbox_element, locator_element = get_checkbox_by_locator(
                locator, anchor)
    if checkbox_element:
        return checkbox_element, locator_element
    raise QWebElementNotFoundError('No matching element found')
Exemplo n.º 12
0
def verify_element(xpath, timeout=0, **kwargs):  # pylint: disable=unused-argument
    r"""Verify that element can be found on the page and it is visible.

    Examples
    --------
    .. code-block:: robotframework

       VerifyElement          //*[@id\="wait_me"]

    This keyword has timeout functionality. If the element is not visible after
    given timeout, error is raised.
    For example.

    .. code-block:: robotframework

        VerifyElement          //*[@id\="wait_me"]       20   #waits 20 seconds

    Parameters
    ----------
    xpath : str
        Xpath expression without xpath= prefix. The equal sign "=" must be escaped with a "\\".
    timeout : str | int
        Timeout for finding the element. If the element is not visible after
        given timeout, error is raised. The str is converted to integer
        using robot.utils.timestr_to_secs. (default 10 seconds)
    kwargs :
        |  Accepted kwargs:
        |       tag : html tag of preferred elemenr -
        |           If tag is used then element is found
        |           by some of it's attribute (xpath is not needed)
        |       partial_match: True. If element is found by it's attribute set partial_match
        |       to True to allow partial match

    Raises
    ------
    QWebElementNotFoundError
        Page did not contain element

    Related keywords
    ----------------
    \`ClickElement\`, \`GetAttribute\`, \`GetWebElement\`, \`GetElementCount\`,
    \`VerifyItem\`, \`VerifyText\`
    """
    kwargs['element_kw'] = True
    if 'tag' in kwargs:
        web_elements = element.get_visible_elements_from_elements(
            element.get_elements_by_attributes(kwargs.get('tag'), xpath,
                                               **kwargs))
    else:
        web_elements = element.get_webelements(xpath, **kwargs)
    if web_elements:
        return
    raise QWebElementNotFoundError('No matching element found')
Exemplo n.º 13
0
def get_element_from_childnodes(locator_element, css, dom_traversing=True, **kwargs):
    limit = util.par2bool(kwargs.get('limit_traverse', CONFIG['LimitTraverse']))
    level = 3 if limit is True else 6
    try:
        web_elements = get_visible_elements_from_elements(
            javascript.get_childnodes(locator_element, css, level, dom_traversing))
    except (WebDriverException, JavascriptException) as e:
        web_elements = None
        logger.debug('Got Exception from get_element_from_childnodes: {}'.format(e))
    if web_elements:
        return web_elements
    raise QWebElementNotFoundError('Child with tag {} not found.'.format(css))
Exemplo n.º 14
0
def _equal_sign_handler(args, kwargs, function_name):
    if 'go_to' in str(function_name):
        if kwargs:
            new_args = []
            for k, v in kwargs.items():
                new_args.append(k)
                new_args.append(v)
            args = tuple(["=".join(map(str, new_args))])
            kwargs.clear()
    try:
        locator = args[0]
    except IndexError:
        raise QWebElementNotFoundError("Use \\= instead of = in xpaths")
    return args, kwargs, locator
Exemplo n.º 15
0
def click_icon(image, template_res_w=None, browser_res_w=None, timeout=0):  # pylint: disable=unused-argument
    r"""Click the icon on the screen.

    In case you want to click icons you always have to have reference images.

    If reference picture are not in default folders (images, files, downloads) then
    BASE_IMAGE_PATH should be defined in a robot file before using this keyword

    Examples
    --------
    .. code-block:: robotframework

        *** Variables ***
        ${BASE_IMAGE_PATH}          ${CURDIR}${/}..${/}resources${/}images

    BASE_IMAGE_PATH should lead to the folder where all your reference icons are

    .. code-block:: robotframework

        ClickIcon                   plane

    Related keywords
    ----------------
    \`ClickCell\`, \`ClickCheckbox\`, \`ClickElement\`,
    \`ClickItem\`, \`ClickList\`, \`ClickText\`,
    \`ClickUntil\`, \`ClickWhile\`, \`VerifyIcon\`
    """
    if not browser_res_w:
        browser_res_w = util.get_monitor_width(
        )  # pyautogui works on whole screen

    # use current resolution by default
    if not template_res_w:
        template_res_w = browser_res_w

    template_res_w, browser_res_w = int(template_res_w), int(browser_res_w)
    image_path = icon.get_full_image_path(image)
    x, y = icon.image_recognition(image_path,
                                  template_res_w,
                                  browser_res_w,
                                  pyautog=True)
    if x == -1:
        raise QWebElementNotFoundError(
            "Couldn't find the icon from the screen")
    if CONFIG.get_value("RetinaDisplay"):
        x = x * 0.5
        y = y * 0.5
    pyautogui.moveTo(x, y)
    pyautogui.click(x, y)
Exemplo n.º 16
0
def get_draggable_element(text, index, anchor):
    attribute_match = '[title^="{0}"][draggable="true"],[alt^="{0}"][draggable="true"],' \
                      '[tooltip^="{0}"][draggable="true"],' \
                      '[data-tooltip^="{0}"][draggable="true"],' \
                      '[data-icon^="{0}"][draggable="true"],' \
                      '[aria-label^="{0}"][draggable="true"],' \
                      '[title^="{0}"][class*="draggableCell"]'.format(text)
    web_elements = []
    matches = []
    if text.startswith('xpath=') or text.startswith('//'):
        web_element = element.get_unique_element_by_xpath(text)
        if web_element:
            return web_element
        raise QWebElementNotFoundError('Draggable element not found by locator {}'.format(text))
    try:
        index = int(index) - 1
    except ValueError as e:
        raise QWebValueError('Index needs to be number') from e
    web_elements = javascript.execute_javascript(
        'return document.querySelectorAll(\'{}\')'.format(attribute_match))
    if web_elements:
        return web_elements[index]
    web_elements = javascript.execute_javascript(
        'return document.querySelectorAll(\'[draggable="true"]\')')
    if web_elements:
        matches = _find_matches(web_elements, text)
        if matches:
            return matches[index]
        if text == 'index':
            logger.warn('Text is not matching to any draggable element. Found {} '
                        'draggable elements. Using index..'.format(len(web_elements)))
            return web_elements[index]
        web_elements = get_text_using_anchor(text, anchor)
        if web_elements:
            return web_elements
    raise QWebElementNotFoundError('Draggable element not found by locator {}'.format(text))
Exemplo n.º 17
0
def get_item_using_anchor(text, anchor, **kwargs):
    xpath = '//*[@title="{0}" or @alt="{0}" or @data-tooltip="{0}" or ' \
            '@tooltip="{0}" or @aria-label="{0}" or @data-icon="{0}"]'.format(text)
    if CONFIG["CssSelectors"]:
        web_elements = _get_item_by_css(text, **kwargs)
    else:
        web_elements = element.get_webelements(xpath, **kwargs)
    if web_elements:
        if CONFIG['SearchMode']:
            element.draw_borders(_get_correct_element(web_elements, str(anchor)))
        return _get_correct_element(web_elements, str(anchor))
    no_raise = util.par2bool(kwargs.get('allow_non_existent', False))
    if no_raise:
        return None
    raise QWebElementNotFoundError('Cannot find item for locator {}'.format(text))
Exemplo n.º 18
0
 def create_list(self, locator, anchor, **kwargs):
     if locator.startswith('//') or locator.startswith('xpath='):
         if locator.startswith('xpath='):
             locator = locator.split("=", 1)[1]
         web_elements = self.get_elements_by_locator_xpath_and_tag_name(
             locator, anchor, **kwargs)
     else:
         web_elements = self.get_elements_by_locator_text_and_tag_name(
             locator, anchor, **kwargs)
         logger.debug('webelems: {}'.format(web_elements))
     if web_elements:
         if CONFIG['SearchMode']:
             element.draw_borders(web_elements)
         web_list = self.get_texts(web_elements)
         return web_list, web_elements
     raise QWebElementNotFoundError('Suitable elements not found')
Exemplo n.º 19
0
def _execute_block(steps, timeout=0, **kwargs):  # pylint: disable=unused-argument
    logger.trace('Timeout for block: {}'.format(timeout))
    logger.trace(steps)
    for step in steps:
        fn = step.get('paceword')
        var_name = step.get('variable', None)
        args = blocks.set_robot_args(*step.get('args'), **step.get('kwargs'))
        status, res = BuiltIn().run_keyword_and_ignore_error(fn, *args)
        logger.trace('status: {}, res: {}'.format(status, res))
        if status == 'FAIL':
            teardown = kwargs.get('exp_handler', None)
            if teardown:
                BuiltIn().run_keyword_and_ignore_error(teardown)
            raise QWebElementNotFoundError('Err from block {}'.format(res))
        if var_name:
            BuiltIn().set_suite_variable('{}'.format(var_name), res)
Exemplo n.º 20
0
def get_text_using_anchor(text, anchor, **kwargs):
    """Get WebElement that contains text using anchor if necessary.

    First locates the elements that has the exact text. If no elements were
    found then searching as a substring using XPath's contains function. If
    we come up empty then NoSuchElementException is raised.

    If text corresponded to multiple elements then anchor is taken in to
    play.

    Parameters
    ----------
    text : str
        Text on web page that is wanted to locate.
    anchor : str
        Unique text on web page which is close to the first argument.
    Accepted kwargs:
        css=False/off: Use this to bypass css search when finding elements
        by visible text

    Returns
    -------
    WebElement
    """
    web_elements = get_all_text_elements(text, **kwargs)
    modal_xpath = CONFIG['IsModalXpath']

    driver = browser.get_current_browser()
    if modal_xpath != "//body":
        # filter elements by modal (dialog etc)
        logger.debug("IsModalXpath filtering on, filtering...")
        modal_exists = driver.find_elements(By.XPATH, modal_xpath)
        if modal_exists:
            web_elements = _filter_by_modal_ancestor(web_elements)
            logger.debug(
                f"after filtering there are: {len(web_elements)} matching elements"
            )
            if not web_elements:
                raise QWebElementNotFoundError(
                    'Webpage did not contain text "{}"'.format(text))

    if len(web_elements) == 1:
        return web_elements[0]
    # Found many elements, use anchors to determine correct element
    correct_element = get_element_using_anchor(web_elements, anchor, **kwargs)
    return correct_element
Exemplo n.º 21
0
def get_all_text_elements(text, **kwargs):
    """Get all webelements found by text"""
    web_elements = []
    all_text_nodes = util.par2bool(kwargs.get('all_text_nodes', CONFIG['AllTextNodes']))
    kwargs['partial_match'] = kwargs.get('partial_match', CONFIG['PartialMatch'])
    if all_text_nodes:
        web_elements = check_all_nodes(text, **kwargs)
        if web_elements:
            return web_elements
    if 'css' not in kwargs:
        try:
            web_elements = get_clickable_element_by_js(text, **kwargs)
        except (JavascriptException, WebDriverException, NoSuchFrameException,
                QWebStalingElementError) as e:
            logger.debug('got {}. Syntax might be invalid'.format(e))
    if not web_elements:
        web_elements = get_text_elements(text, **kwargs)
    if not web_elements:
        raise QWebElementNotFoundError('Webpage did not contain text "{}"'.format(text))
    return web_elements
Exemplo n.º 22
0
def get_closest_element(locator_element, candidate_elements):
    """Get the closest element in a list of elements to a wanted element.

    Parameters
    ----------
    locator_element : WebElement
    candidate_elements : :obj:`list` of :obj:`WebElement`

    Returns
    -------
    WebElement
    """
    if not candidate_elements:
        raise QWebElementNotFoundError('No elements visible')
    closest_element_list = []
    closest_distance = 1000000  # Just some large number
    for candidate_element in candidate_elements:
        element_info = _list_info(candidate_element)
        logger.debug("Measuring distance for: {}".format(element_info))
        if _overlap(locator_element, candidate_element):
            logger.debug(
                'Elements overlap, returning this: {}'.format(element_info))
            return candidate_element
        distance = _calculate_closest_distance(locator_element,
                                               candidate_element)
        logger.debug("Candidate {}: distance: {}".format(
            candidate_element, distance))

        if abs(distance - closest_distance) < 2:
            closest_element_list.append(candidate_element)
            closest_distance = distance
        elif distance < closest_distance:
            closest_distance = distance
            closest_element_list = [candidate_element]

    closest_element = _get_closest_ortho_element(locator_element,
                                                 closest_element_list)

    logger.debug("Closest distance found is {}".format(closest_distance))
    logger.debug("Closest element is: {}".format(_list_info(closest_element)))
    return closest_element
Exemplo n.º 23
0
 def get_table_element(self, locator, anchor):
     if util.xpath_validator(locator):
         table_element = element.get_unique_element_by_xpath(locator)
     else:  # Search using text
         table_xpath = "//*[text()= '{0}']/ancestor::table".format(locator)
         table_elements = element.get_webelements_in_active_area(
             table_xpath)
         if table_elements and len(table_elements) == 1:
             table_element = table_elements[0]
         elif not table_elements:  # Find table element using locator
             locator_element = text.get_text_using_anchor(locator, anchor)
             table_elements = self._get_all_table_elements()
             table_element = element.get_closest_element(
                 locator_element, table_elements)
         else:  # Found many
             table_element = text.get_element_using_anchor(
                 table_elements, anchor)
     if table_element:
         return table_element
     raise QWebElementNotFoundError(
         'Table element not found by locator {}'.format(locator))
Exemplo n.º 24
0
 def get_table_cell(self, coordinates, anchor, **kwargs):  # pylint: disable=unused-argument
     cell = None
     try:
         if '/' in coordinates:
             cell = self.get_using_text_in_coordinates(coordinates, anchor)
         else:
             row, column = self._convert_coordinates(coordinates)
             try:
                 cell = self.table.find_element(
                     By.XPATH, './/tr[{0}]//td[{1}]'.format(row, column))
             except AttributeError as e:
                 logger.debug('exception {}'.format(e))
                 self.update_table()
         if cell:
             if CONFIG['SearchMode']:
                 element.draw_borders(cell)
             return cell
     except (StaleElementReferenceException, NoSuchElementException) as e:
         logger.debug('exception {}'.format(e))
         self.update_table()
     raise QWebElementNotFoundError(
         'Cell for coords {} not found after'.format(coordinates))
Exemplo n.º 25
0
    def get_elements_from_dom_content(*args, **kwargs):
        try:
            args, kwargs, locator = _equal_sign_handler(args, kwargs, fn)
            msg = None
            params = signature(fn).parameters
            args, kwargs = _args_to_kwargs(params, args, kwargs)
            timeout = get_timeout(**kwargs)
            logger.debug('Timeout is {} sec'.format(timeout))

            try:
                if 'go_to' not in str(fn) and 'switch_window' not in str(fn):
                    frame.wait_page_loaded()
            except UnexpectedAlertPresentException as e:
                if not CONFIG["HandleAlerts"]:
                    raise QWebUnexpectedAlert(str(e))
                logger.debug('Got {}. Trying to retry..'.format(e))
                time.sleep(SHORT_DELAY)
            start = time.time()
            while time.time() < timeout + start:
                try:
                    kwargs['timeout'] = float(timeout + start - time.time())
                    config.set_config('FrameTimeout',
                                      float(timeout + start - time.time()))
                    return fn(*args, **kwargs)
                except (QWebUnexpectedConditionError, QWebTimeoutError) as e:
                    logger.warn('Got {}'.format(e))
                except (InvalidSelectorException, NoSuchElementException,
                        QWebElementNotFoundError,
                        UnexpectedAlertPresentException,
                        QWebStalingElementError,
                        StaleElementReferenceException,
                        QWebIconNotFoundError) as e:
                    time.sleep(SHORT_DELAY)
                    logger.debug(
                        'Got exception: {}. Trying to retry..'.format(e))
                except InvalidSessionIdException:
                    CONFIG.set_value("OSScreenshots", True)
                    raise QWebBrowserError(
                        "Browser session lost. Did browser crash?")
                except (WebDriverException, QWebDriverError) as e:
                    if any(s in str(e) for s in FATAL_MESSAGES):
                        CONFIG.set_value("OSScreenshots", True)
                        raise QWebBrowserError(e)
                    logger.info(
                        'From timeout decorator: Webdriver exception. Retrying..'
                    )
                    logger.info(e)
                    time.sleep(SHORT_DELAY)
                    err = QWebDriverError
                    msg = e
                except QWebValueError as ve:
                    logger.debug(
                        'Got QWebValueError: {}. Trying to retry..'.format(ve))
                    err = QWebValueError
                    msg = ve
                    time.sleep(SHORT_DELAY)
            if msg:
                raise err(msg)
            if 'count' in str(fn):
                return 0
            if 'is_text' in str(fn) or 'is_no_text' in str(fn):
                return False
            raise QWebElementNotFoundError(
                'Unable to find element for locator {} in {} sec'.format(
                    locator, timeout))
        except QWebSearchingMode:
            pass
Exemplo n.º 26
0
def get_attribute(locator,
                  attribute,
                  anchor='1',
                  element_type=None,
                  timeout=0,
                  **kwargs):
    r"""Get attribute value of an element.

    Examples
    --------
    Using attributes or xpaths like with ClickElement etc. kw:s without specified
    element_type. If element_type is not specified end result is a type of list:

    .. code-block:: robotframework

        ${attribute_value}  GetAttribute            click_me     id         tag=button
        ${attribute_value}  GetAttribute            //*[@id\="click_me"]    id
        ${attribute_value}  GetAttribute            xpath\=//*[@id\="click_me"] name

    GetAttribute using element_type attribute to locate element.
    Text elements works as ClickText, VerifyText, GetText etc.:

    .. code-block:: robotframework

        ${attribute_value}   GetAttribute     Log In    type    element_type=text
        ${attribute_value}   GetAttribute     Contact   id      element_type=text  anchor=Qentinel
        ${attribute_value}   GetAttribute     Contact   class   parent=div

    Item, Input, Dropdown, Checkbox elements:

    .. code-block:: robotframework

        ${attribute_value}  GetAttribute          Log In    id              element_type=item
        ${attribute_value}  GetAttribute          Username  placeholder     element_type=input
        ${attribute_value}  GetAttribute          Country   value           element_type=dropdown
        ${attribute_value}  GetAttribute          Gender    checked         element_type=checkbox

    All flags are available for using (timeout, anchor, index, visibility, parent, child etc.).
    in same way as you are using those with Pacewords like ClickText/Item, TypeText, Dropdown etc.

    Parameters
    ----------
    locator : str
        Visible text, attribute value or Xpath expression with or without xpath= prefix.
        The equal sign "=" must be escaped with a "\\".
    attribute: str
        Attribute which value we want to get.
    anchor : int
        Used when element_type is defined. Default=1 (first match)
    element_type : string
        Define element type/preferred searching method
        (available types: text, input, checkbox, item, dropdown).
    timeout : int
        How long we wait element to appear. Default=10 sec
    kwargs :
        |  Accepted kwargs:
        |       Any available for picked searching method.
        |       See interacting with text, item, input etc. elements from
        |       documentation

    Returns
    -------
    value : Value of attribute (true if attribute exist but does not have value)

    Related keywords
    ----------------
    \`VerifyAttribute\`, \`VerifyElement\`
    """
    webelement = get_webelement(locator, anchor, element_type, timeout,
                                **kwargs)

    if not webelement:
        raise QWebElementNotFoundError(
            'Could not find element {} with attribute {}'.format(
                locator, attribute))
    if not isinstance(webelement, list):
        return webelement.get_attribute(attribute)

    if len(webelement) == 1:
        return webelement[0].get_attribute(attribute)

    raise QWebValueError(
        'Found {} occurences of locator {}. '
        'Use index etc. to uniquely identify the element'.format(
            len(webelement), locator))
Exemplo n.º 27
0
def get_parent_element(web_element, tag):
    web_element = javascript.execute_javascript(
        'return arguments[0].closest(\'{}\')'.format(tag), web_element)
    if web_element:
        return web_element
    raise QWebElementNotFoundError('Parent with tag {} not found.'.format(tag))
Exemplo n.º 28
0
def get_webelement(locator,
                   anchor='1',
                   element_type=None,
                   timeout=0,
                   **kwargs):
    r"""Get Webelement using any Paceword -stylish locator.

    Examples
    --------
    Using attributes or xpaths like with ClickElement etc. kw:s without specified
    element_type. If element_type is not specified end result is a type of list:

    .. code-block:: robotframework

        ${list of elems}    GetWebelement          click_me      tag=button
        ${list of elems}    GetWebelement          //*[@id\="click_me"]
        ${list of elems}    GetWebelement          xpath\=//*[@id\="click_me"]

    Get element using element_type attribute to locate element.
    Text elements works as ClickText, VerifyText, GetText etc.:

    .. code-block:: robotframework

        ${elem}      GetWebelement          Log In    element_type=text
        ${elem}      GetWebelement          Contact   element_type=text  anchor=Qentinel
        ${elem}      GetWebelement          Contact   parent=div

    Item, Input, Dropdown, Checkbox elements:

    .. code-block:: robotframework

        ${elem}      GetWebelement          Log In    element_type=item
        ${elem}      GetWebelement          Username  element_type=input
        ${elem}      GetWebelement          Country   element_type=dropdown
        ${elem}      GetWebelement          Gender    element_type=checkbox

    All flags are available for using (timeout, anchor, index, visibility, parent, child etc.).
    in same way as you are using those with Pacewords like ClickText/Item, TypeText, Dropdown etc.

    Parameters
    ----------
    locator : str
        Visible text, attribute value or Xpath expression with or without xpath= prefix.
        The equal sign "=" must be escaped with a "\\".
    anchor : int
        Used when element_type is defined. Default=1 (first match)
    element_type : string
        Define element type/preferred searching method
        (available types: text, input, checkbox, item, dropdown).
    timeout : int
        How long we wait element to appear. Default=10 sec
    kwargs :
        |  Accepted kwargs:
        |       Any available for picked searching method.
        |       See interacting with text, item, input etc. elements from
        |       documentation

    Related keywords
    ----------------
    \`ClickElement\`, \`HoverElement\`, \`TypeText\`
    """
    kwargs['index'] = kwargs.get('index', 1)
    kwargs['timeout'] = timeout
    if element_type:
        if element_type.lower() == 'text':
            return text.get_element_by_locator_text(locator, anchor, **kwargs)
        if element_type.lower() == 'item':
            return text.get_item_using_anchor(locator, anchor, **kwargs)
        if element_type.lower() == "dropdown":
            return dropdown.get_dd_elements_from_all_documents(
                locator, anchor, **kwargs)
        if element_type.lower() == "input":
            return input_.get_input_elements_from_all_documents(
                locator, anchor, **kwargs)
        if element_type.lower() == "checkbox":
            return checkbox.get_checkbox_elements_from_all_documents(
                locator, anchor, **kwargs)
    kwargs['element_kw'] = True
    if 'tag' in kwargs:
        web_elements = element.get_visible_elements_from_elements(
            element.get_elements_by_attributes(kwargs.get('tag'), locator,
                                               **kwargs))
    else:
        web_elements = element.get_webelements(locator)
    if web_elements:
        return web_elements
    raise QWebElementNotFoundError('No matching element found')
Exemplo n.º 29
0
def get_input_elements_from_all_documents(locator,
                                          anchor,
                                          timeout,
                                          index=1,
                                          enable_check=False,
                                          **kwargs):  # pylint: disable=unused-argument
    """Function for finding input elements.
    Parameters
    ----------
    locator : str
       Label text or attribute that points to the checkbox.
    anchor : str
       in case there is duplicates.
    timeout : str
       How long we are finding before fail.
       Default = Search Strategy global default = 10 sec)
    index : int
       If table cell contains more than one input elements or if there is some kind of
       nested structure inside of given input index may needed. Default = 1 (first)
    enable_check : bool
        When CSS Selectors are used, we are not return disabled input element
        always by default. Element is needed with verify input status kw
        so if enable_check= True, disabled input_element is returned
    kwargs:
        limit_traverse : bool
            If set to false. We are heading up to fifth parent element if needed when
            finding relative input element for some label text.
    Returns
    -------
    WebElement
    """
    index = int(index) - 1
    css = 'input:not([type="hidden"]):not([type="submit"]):not([type="button"])' \
          ':not([type="reset"]):not([type="checkbox"]):not([type="radio"])' \
          ':not([aria-hidden="true"]),' \
          'textarea:not([type="hidden"]),[contenteditable="true"]'
    kwargs['css'] = kwargs.get('css', css)
    if Table.is_table_coordinates(locator):
        table = Table.ACTIVE_TABLE.update_table()
        if table is None:
            raise QWebInstanceDoesNotExistError(
                'Table has not been defined with UseTable keyword')
        locator_element = table.get_table_cell(locator, anchor)
        input_element = element.get_element_from_childnodes(
            locator_element, kwargs['css'], dom_traversing=False)
        if input_element:
            return input_element[index]
        raise QWebElementNotFoundError('No matching table input found')
    css_selector = CONFIG["CssSelectors"]
    if not css_selector or locator.startswith('xpath=') or locator.startswith(
            '//'):
        input_element = get_input_element_by_locator(locator, anchor, **kwargs)
    else:
        logger.debug('Uses CSS-selectors to locate element')
        input_element = get_input_element_by_css_selector(
            locator, anchor, index, enable_check, **kwargs)
        if not input_element:
            input_element = get_input_element_by_locator(
                locator, anchor, **kwargs)
    if input_element:
        if CONFIG['SearchMode']:
            element.draw_borders(input_element)
        return input_element
    raise QWebElementNotFoundError('No matching input elements found')