Esempio 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')
Esempio n. 2
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')
Esempio n. 3
0
def get_checkbox_by_css_selector(locator, anchor, index, **kwargs):
    """Get checkbox using css selectors."""
    checkbox_elements = []
    partial_matches = []
    css = '[type="checkbox"], [role="checkbox"]'
    if 'qweb_old' not in kwargs:
        full_matches, partial_matches = element.get_elements_by_css(
            locator, css, **kwargs)
        if full_matches:
            checkbox_elements = element.get_visible_elements_from_elements(
                full_matches, **kwargs)
            if checkbox_elements:
                return checkbox_elements[index], None
    try:
        locator_element = text.get_text_using_anchor(locator, anchor)
        checkbox_elements = list(
            dict.fromkeys(
                element.get_element_from_childnodes(locator_element, css, **
                                                    kwargs) + partial_matches))
        return checkbox_elements[index], locator_element
    except QWebElementNotFoundError:
        logger.trace(
            'Element not found by visible text. Trying with partial match')
        checkbox_elements = partial_matches
    if checkbox_elements:
        logger.debug("Found element {}, index {}".format(
            checkbox_elements, index))
        return checkbox_elements[index], None
    return None, None
Esempio n. 4
0
 def get_clickable_cell(self, coordinates, anchor, index=1, **kwargs):
     index = int(index) - 1
     table_cell = self.get_table_cell(coordinates, anchor)
     if 'tag' in kwargs:
         clickable_child = element.get_element_from_childnodes(
             table_cell, kwargs.get('tag'), dom_traversing=False)
         return clickable_child[index]
     return table_cell
Esempio n. 5
0
 def get_clickable_cell(self, coordinates, anchor, index=1, **kwargs):
     if int(index) < 1:
         raise QWebValueError('Index should be greater than 0.')
     table_cell = self.get_table_cell(coordinates, anchor)
     if 'tag' in kwargs:
         clickable_child = element.get_element_from_childnodes(
             table_cell, kwargs.get('tag'), dom_traversing=False)
         if int(index) > len(clickable_child):
             raise QWebValueError(
                 'Index exceeds the number of clickable elements in cell.')
         return clickable_child[int(index) - 1]
     return table_cell
Esempio n. 6
0
def get_dropdown_element_by_css_selector(locator, anchor, index, **kwargs):
    """Get Dropdown element using css selectors.
       Parameters
       ----------
       locator : str
           Label text or attribute that points to the dropdown.
           Looking for placeholder and commonly used tooltip-attributes first.
           If locator is label text, finds input element by it's for attribute.
           if for attribute is not available, then finds element by doing some
           DOM traversing.
       anchor : str
           Using if locator is not an XPath.
       index : int
           If multiple elements use index to pick correct one.
       Returns
       -------
       WebElement
   """
    dropdown_elements = []
    partial_matches = []
    css = 'select'
    if 'qweb_old' not in kwargs:
        full_matches, partial_matches = element.get_elements_by_css(
            locator, css, **kwargs)
        if full_matches:
            if index != 0:
                try:
                    return full_matches[index]
                except IndexError as e:
                    raise QWebInstanceDoesNotExistError(
                        f'Found {len(full_matches)} elements. Given index was {index}'
                    ) from e
            correct_element = text.get_element_using_anchor(
                full_matches, anchor)
            return correct_element
    try:
        locator_element = text.get_text_using_anchor(locator, anchor)
        # if this is option, return parent select immediately
        if locator_element.tag_name.lower() == "option":
            return javascript.execute_javascript(
                "return arguments[0].parentNode;", locator_element)
        dropdown_elements = list(
            dict.fromkeys(
                element.get_element_from_childnodes(locator_element, css, **
                                                    kwargs) + partial_matches))
    except QWebElementNotFoundError:
        logger.trace(
            'Element not found by visible text. Trying with partial match')
        dropdown_elements = partial_matches
    if dropdown_elements:
        return dropdown_elements[index]
    return None
Esempio n. 7
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')
Esempio n. 8
0
    def get_elements_by_locator_xpath_and_tag_name(locator, index=1, **kwargs):
        index = int(index) - 1
        if 'tag' in kwargs:
            tag_name = kwargs.get('tag')
        elif 'parent' in kwargs and kwargs['parent']:
            tag_name = kwargs['parent']
        elif 'child' in kwargs and kwargs['child']:
            tag_name = kwargs['child']
        else:
            tag_name = 'ul'
        if 'parent' in kwargs and kwargs['parent']:
            web_element = element.get_unique_element_by_xpath(locator)
            css = kwargs.get('parent')
            web_element = element.get_parent_list_element(web_element, css)
            if tag_name not in ["ul", "ol", "dl", "UL", "OL", "DL"]:
                web_element = javascript.execute_javascript(
                    'return arguments[0].querySelectorAll("{}")'.format(
                        tag_name), web_element)
            else:
                web_element = javascript.execute_javascript(
                    'return arguments[0].closest("{}").querySelectorAll("li, dt, dd")'
                    .format(tag_name), web_element)
        elif 'child' in kwargs and kwargs['child']:
            web_element = element.get_unique_element_by_xpath(locator)
            css = kwargs.get('child')
            web_element = element.get_element_from_childnodes(
                web_element, css, dom_traversing=False)[index]
            if tag_name not in ["ul", "ol", "dl", "UL", "OL", "DL"]:
                web_element = javascript.execute_javascript(
                    'return arguments[0].querySelectorAll("{}")'.format(
                        tag_name), web_element)
            else:
                web_element = javascript.execute_javascript(
                    'return arguments[0].closest("{}").querySelectorAll("li, dt, dd")'
                    .format(tag_name), web_element)
        else:
            web_element = element.get_webelements_in_active_area(locator)

        return web_element
Esempio n. 9
0
    def get_elements_by_locator_text_and_tag_name(locator,
                                                  anchor,
                                                  index=1,
                                                  **kwargs):
        index = int(index) - 1
        if 'tag' in kwargs:
            tag_name = kwargs.get('tag')
        elif 'parent' in kwargs and kwargs['parent']:
            tag_name = kwargs['parent']
        elif 'child' in kwargs and kwargs['child']:
            tag_name = kwargs['child']
        else:
            tag_name = 'ul'

        web_element = text.get_element_by_locator_text(locator, anchor)
        if 'parent' in kwargs and kwargs['parent']:
            tag = kwargs['parent']
            locator_element = element.get_parent_list_element(web_element, tag)
        elif 'child' in kwargs and kwargs['child']:
            tag = kwargs['child']
            locator_element = element.get_element_from_childnodes(
                web_element, tag, dom_traversing=False)[index]
            if tag_name not in ["ul", "ol", "dl", "UL", "OL", "DL"]:
                return locator_element
        else:
            locator_element = text.get_element_by_locator_text(locator, anchor)

        if tag_name not in ["ul", "ol", "dl", "UL", "OL", "DL"]:
            web_elements = javascript.execute_javascript(
                'return arguments[0].querySelectorAll("{}")'.format(tag_name),
                locator_element)
        else:
            web_elements = javascript.execute_javascript(
                'return arguments[0].closest("{}").querySelectorAll("li, dt, dd")'
                .format(tag_name), locator_element)
        return web_elements
Esempio n. 10
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')
Esempio n. 11
0
def get_input_element_by_css_selector(locator,
                                      anchor,
                                      index=0,
                                      enable_check=False,
                                      **kwargs):
    """Get input element using css selectors.
       Parameters
       ----------
       locator : str
           Label text or attribute that points to the input.
           Looking for placeholder and commonly used tooltip-attributes first.
           If locator is label text, finds input element by it's for attribute.
           if for attribute is not available, then finds element by doing some
           DOM traversing.
       anchor : str
           Text near the locator element or index. If placeholder or another
           direct attribute (title, tooltip, value) exists then anchor
           has to be index. Text is aloud when searching by label or some other
           text which is near to input element.
       index: int
            If multiple input elements is nested or in same table cell, index is needed.
       enable_check: bool
            If enable_check is set to true returns first match even if disabled one.
       Returns
       -------
       WebElement
       """
    partial_matches = []
    upload = kwargs.get('upload')
    if upload:
        try:
            index = int(locator) - 1
            kwargs['any_element'] = True
            input_elements = element.get_elements_by_attributes(**kwargs)
            if input_elements:
                return input_elements[index]
        except ValueError:
            logger.debug('locator was text')
    if 'qweb_old' not in kwargs:
        full_matches, partial_matches = element.get_elements_by_css(
            locator, **kwargs)
        if full_matches:
            input_element = element.get_visible_elements_from_elements(
                full_matches, **kwargs)
            if input_element and str(anchor) == '1':
                input_element = input_element[index]
                return input_element
            if input_element:
                input_element = text.get_element_using_anchor(
                    input_element, anchor, **kwargs)
                return input_element
    try:
        locator_element = text.get_text_using_anchor(locator, anchor, **kwargs)
        input_elements = list(
            dict.fromkeys(
                element.get_element_from_childnodes(locator_element, **kwargs)
                + partial_matches))
    except QWebElementNotFoundError:
        logger.trace(
            'Element not found by visible text. Trying with partial match')
        input_elements = partial_matches
    if input_elements:
        visibles = element.get_visible_elements_from_elements(
            input_elements, **kwargs)
        if visibles:
            if element.is_enabled(visibles[index]) or enable_check is True:
                return visibles[index]
    return None