Python selenium.webdriver.remote.webelement.WebElement() Examples

The following are 30 code examples of selenium.webdriver.remote.webelement.WebElement(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module selenium.webdriver.remote.webelement , or try the search function .
Example #1
Source File: driver_utils.py    From toolium with Apache License 2.0 8 votes vote down vote up
def _expected_condition_value_in_element_attribute(self, element_attribute_value):
        """Tries to find the element and checks that it contains the requested attribute with the expected value,
           but does not thrown an exception if the element is not found

        :param element_attribute_value: Tuple with 3 items where:
            [0] element: PageElement or element locator as a tuple (locator_type, locator_value) to be found
            [1] attribute: element's attribute where to check its value
            [2] value: expected value for the element's attribute
        :returns: the web element if it contains the expected value for the requested attribute or False
        :rtype: selenium.webdriver.remote.webelement.WebElement or appium.webdriver.webelement.WebElement
        """
        element, attribute, value = element_attribute_value
        web_element = self._expected_condition_find_element(element)
        try:
            return web_element if web_element and web_element.get_attribute(attribute) == value else False
        except StaleElementReferenceException:
            return False 
Example #2
Source File: row_tests.py    From nerodia with MIT License 6 votes vote down vote up
def selector_built(mocker, **opts):
    klass = opts.pop('element', HTMLElement)
    mock = mocker.MagicMock(spec=klass)
    mock.enabled = True
    if 'wd' in opts:
        mock.wd = opts.pop('wd')
    else:
        mock.wd = mocker.MagicMock(spec=WebElement)
    if 'selector' in opts:
        selector = opts.pop('selector')
    else:
        selector = {}
    for key, value in opts.items():
        setattr(mock, key, value)
    mock.selector = selector

    builder = SelectorBuilder(ATTRIBUTES, mock)
    built = builder.build(selector)
    built.pop('scope', None)
    return built 
Example #3
Source File: element_operations.py    From warriorframework with Apache License 2.0 6 votes vote down vote up
def _drag_and_drop_by_offset(self, source, **kwargs):
        """Holds down the left mouse button on the source element,
           then moves to the target offset and releases the mouse button
        :Arguments:
            1. source  = a valid WebElement
            2. xoffset = X offset to move to
            3. yoffset = Y offset to move to
        """
        status = True
        print_info("drag and drop an element with offset")
        try:
            xoffset = kwargs.get('xoffset')
            yoffset = kwargs.get('yoffset')
            browser_instance = kwargs.get('browser')
            actions = ActionChains(browser_instance)
            actions.drag_and_drop_by_offset(source, xoffset, yoffset).perform()
        except NoSuchElementException as e:
            print_error("NoSuchElementException occurred")
            status = False
        except Exception as e:
            print_error("An Exception Occurred {}".format(e))
            status = False
        return status 
Example #4
Source File: driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def swipe(self, element, x, y, duration=None):
        """Swipe over an element

        :param element: either a WebElement, PageElement or element locator as a tuple (locator_type, locator_value)
        :param x: horizontal movement
        :param y: vertical movement
        :param duration: time to take the swipe, in ms
        """
        if not self.driver_wrapper.is_mobile_test():
            raise Exception('Swipe method is not implemented in Selenium')

        # Get center coordinates of element
        center = self.get_center(element)
        initial_context = self.driver_wrapper.driver.current_context
        if self.driver_wrapper.is_web_test() or initial_context != 'NATIVE_APP':
            center = self.get_native_coords(center)

        # Android needs absolute end coordinates and ios needs movement
        end_x = x if self.driver_wrapper.is_ios_test() else center['x'] + x
        end_y = y if self.driver_wrapper.is_ios_test() else center['y'] + y
        self.driver_wrapper.driver.swipe(center['x'], center['y'], end_x, end_y, duration)

        if self.driver_wrapper.is_web_test() or initial_context != 'NATIVE_APP':
            self.driver_wrapper.driver.switch_to.context(initial_context) 
Example #5
Source File: element_operations.py    From warriorframework with Apache License 2.0 6 votes vote down vote up
def _send_keys(self, element, **kwargs):
        """Send values to a particular element,
        simulates typing into a element
        :Arguments:
            1. element = a valid WebElement
            2. value = a Keys object that has to be sent to the element.
        """
        status = True
        value = kwargs.get('value', '')
        try:
            KEYS[value.upper()]
        except KeyError:
            print_error("{0} is not supported by Selenium.".format(value))
            status = False
        else:
            print_info("Type text='{0}' into element".format(value))
            element.send_keys(KEYS[value.upper()])
        return status 
Example #6
Source File: entity.py    From selene with MIT License 6 votes vote down vote up
def set_value(self, value: Union[str, int]) -> Element:
        # todo: should we move all commands like following or queries like in conditions - to separate py modules?
        # todo: should we make them webelement based (Callable[[WebElement], None]) instead of element based?
        def fn(element: Element):
            webelement = element()
            webelement.clear()  # todo: change to impl based not on clear, because clear generates post-events...
            webelement.send_keys(str(value))

        from selene.core import command
        self.wait.for_(command.js.set_value(value) if self.config.set_value_by_js
                       else Command(f'set value: {value}', fn))

        # todo: consider returning self.cached, since after first successful call,
        #       all next ones should normally pass
        #       no waiting will be needed normally
        #       if yes - then we should pass fn commands to wait.for_ so the latter will return webelement to cache
        #       also it will make sense to make this behaviour configurable...
        return self 
Example #7
Source File: driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def _expected_condition_find_element_containing_text(self, element_text_pair):
        """Tries to find the element and checks that it contains the specified text, but does not thrown an exception if the element is
            not found

        :param element_text_pair: Tuple with 2 items where:
            [0] element: PageElement or element locator as a tuple (locator_type, locator_value) to be found
            [1] text: text to be contained into the element
        :returns: the web element if it contains the text or False
        :rtype: selenium.webdriver.remote.webelement.WebElement or appium.webdriver.webelement.WebElement
        """
        element, text = element_text_pair
        web_element = self._expected_condition_find_element(element)
        try:
            return web_element if web_element and text in web_element.text else False
        except StaleElementReferenceException:
            return False 
Example #8
Source File: element_operations.py    From warriorframework with Apache License 2.0 6 votes vote down vote up
def _type_keys(self, element, **kwargs):
        """Send values to a particular element,
        simulates typing into a element
        :Arguments:
            1. element = a valid WebElement
            2. value = a string that has to be typed into the element.
        """
        status = True
        value = kwargs.get('value', '')
        print_info("Sending '{0}' to element".format(value))
        try:
            element.send_keys(value)
        except Exception as e:
            print_error("An Exception Occurred {}".format(e))
            status = False
        return status 
Example #9
Source File: driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def _expected_condition_find_element_stopped(self, element_times):
        """Tries to find the element and checks that it has stopped moving, but does not thrown an exception if the element
            is not found

        :param element_times: Tuple with 2 items where:
            [0] element: PageElement or element locator as a tuple (locator_type, locator_value) to be found
            [1] times: number of iterations checking the element's location that must be the same for all of them
            in order to considering the element has stopped
        :returns: the web element if it is clickable or False
        :rtype: selenium.webdriver.remote.webelement.WebElement or appium.webdriver.webelement.WebElement
        """
        element, times = element_times
        web_element = self._expected_condition_find_element(element)
        try:
            locations_list = [tuple(web_element.location.values()) for i in range(int(times)) if not time.sleep(0.001)]
            return web_element if set(locations_list) == set(locations_list[-1:]) else False
        except StaleElementReferenceException:
            return False 
Example #10
Source File: test_utils.py    From sos-notebook with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def execute_cell(self,
                     cell_or_index=None,
                     in_console=False,
                     expect_error=False):
        if isinstance(cell_or_index, int):
            index = cell_or_index
        elif isinstance(cell_or_index, WebElement):
            index = self.index(cell_or_index)
        else:
            raise TypeError("execute_cell only accepts a WebElement or an int")
        self._focus_cell(index)
        if in_console:
            self.current_cell.send_keys(Keys.CONTROL, Keys.SHIFT, Keys.ENTER)
            self._wait_for_done(-1, expect_error)
        else:
            self.current_cell.send_keys(Keys.CONTROL, Keys.ENTER)
            self._wait_for_done(index, expect_error) 
Example #11
Source File: driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def _expected_condition_find_element(self, element):
        """Tries to find the element, but does not thrown an exception if the element is not found

        :param element: PageElement or element locator as a tuple (locator_type, locator_value) to be found
        :returns: the web element if it has been found or False
        :rtype: selenium.webdriver.remote.webelement.WebElement or appium.webdriver.webelement.WebElement
        """
        from toolium.pageelements.page_element import PageElement
        web_element = False
        try:
            if isinstance(element, PageElement):
                # Use _find_web_element() instead of web_element to avoid logging error message
                element._web_element = None
                element._find_web_element()
                web_element = element._web_element
            elif isinstance(element, tuple):
                web_element = self.driver_wrapper.driver.find_element(*element)
        except NoSuchElementException:
            pass
        return web_element 
Example #12
Source File: test_derived_page_element.py    From toolium with Apache License 2.0 6 votes vote down vote up
def driver_wrapper():
    # Create a mock element
    global mock_element
    mock_element = mock.MagicMock(spec=WebElement)
    mock_element.find_element.return_value = child_element
    mock_element.text = 'text value'
    mock_element.get_attribute.return_value = 'input text value'

    # Reset wrappers pool values
    DriverWrappersPool._empty_pool()
    DriverWrapper.config_properties_filenames = None

    # Create a new wrapper
    driver_wrapper = DriverWrappersPool.get_default_wrapper()
    driver_wrapper.driver = mock.MagicMock()

    return driver_wrapper 
Example #13
Source File: _element.py    From robotframework-appiumlibrary with Apache License 2.0 6 votes vote down vote up
def _element_find(self, locator, first_only, required, tag=None):
        application = self._current_application()
        elements = None
        if isstr(locator):
            _locator = locator
            elements = self._element_finder.find(application, _locator, tag)
            if required and len(elements) == 0:
                raise ValueError("Element locator '" + locator + "' did not match any elements.")
            if first_only:
                if len(elements) == 0: return None
                return elements[0]
        elif isinstance(locator, WebElement):
            if first_only:
                return locator
            else:
                elements = [locator]
        # do some other stuff here like deal with list of webelements
        # ... or raise locator/element specific error if required
        return elements 
Example #14
Source File: find.py    From webium with Apache License 2.0 6 votes vote down vote up
def __init__(self, ui_type=WebElement,
                 by=None,
                 value=None,
                 context=None,
                 *args,
                 **kwargs):
        self.by = by
        self.value = value
        if self.value and not self.by:
            self.by = webium.settings.default_search_type
        self.ui_type = ui_type
        self.context = context
        self._target_element = None
        self.init_args = args
        self.init_kwargs = kwargs
        self._validate_params() 
Example #15
Source File: test_page_object.py    From toolium with Apache License 2.0 6 votes vote down vote up
def driver_wrapper():
    """Create a new mock element and a new driver before each test"""
    global mock_element
    mock_element = mock.MagicMock(spec=WebElement)
    mock_element.find_element.return_value = child_element

    # Reset wrappers pool values
    DriverWrappersPool._empty_pool()
    DriverWrappersPool.output_directory = ''
    DriverWrapper.config_properties_filenames = None

    # Create a new wrapper
    driver_wrapper = DriverWrappersPool.get_default_wrapper()
    driver_wrapper.driver = mock.MagicMock()

    return driver_wrapper 
Example #16
Source File: WebRunner.py    From PyWebRunner with MIT License 6 votes vote down vote up
def find_elements(self, selector):
        '''
        Finds elements by CSS/XPATH selector.

        Parameters
        ----------
        selector: str
            A CSS/XPATH selector to search for. This can be any valid CSS/XPATH selector.

        Returns
        -------
        list of selenium.webdriver.remote.webelement.WebElement or list
            Returns a list of elements or empty list

        '''
        elems = []
        try:
            if selector.startswith('/'):
                elems = self.browser.find_elements_by_xpath(selector)
            else:
                elems = self.browser.find_elements_by_css_selector(selector)
        except NoSuchElementException:
            pass

        return elems 
Example #17
Source File: WebRunner.py    From PyWebRunner with MIT License 6 votes vote down vote up
def find_element(self, selector):
        '''
        Finds an element by CSS/XPATH selector.

        Parameters
        ----------
        selector: str
            A CSS/XPATH selector to search for. This can be any valid CSS/XPATH selector.

        Returns
        -------
        selenium.webdriver.remote.webelement.WebElement or None
            Returns an element or nothing at all

        '''
        elem = None
        try:
            if selector.startswith('/'):
                elem = self.browser.find_element_by_xpath(selector)
            else:
                elem = self.browser.find_element_by_css_selector(selector)
        except NoSuchElementException:
            pass

        return elem 
Example #18
Source File: tv.py    From Kairos with GNU General Public License v3.0 6 votes vote down vote up
def element_exists(browser, locator, delay=CHECK_IF_EXISTS_TIMEOUT, locator_strategy = By.CSS_SELECTOR):
    result = False
    try:
        element = find_element(browser, locator, locator_strategy, delay)
        result = type(element) is WebElement
    except NoSuchElementException:
        log.debug('No such element. SELECTOR=' + locator)
        # print the session_id and url in case the element is not found
        # noinspection PyProtectedMember
        log.debug("In case you want to reuse session, the session_id and _url for current browser session are: {},{}".format(browser.session_id, browser.command_executor._url))
    except TimeoutException:
        log.debug('No such element. SELECTOR=' + locator)
    except Exception as element_exists_error:
        log.error(element_exists_error)
        log.debug("Check your locator: {}".format(locator))
        # noinspection PyProtectedMember
        log.debug("In case you want to reuse session, the session_id and _url for current browser session are: {},{}".format(browser.session_id, browser.command_executor._url))
    finally:
        log.debug("{} ({})".format(str(result), locator))
        return result 
Example #19
Source File: WebRunner.py    From PyWebRunner with MIT License 6 votes vote down vote up
def get_elements(self, selector):
        '''
        Gets elements by CSS selector.

        Parameters
        ----------
        selector: str
            A CSS selector to search for. This can be any valid CSS selector.

        Returns
        -------
        list of selenium.webdriver.remote.webelement.WebElement
            A list of selenium element objects.

        '''
        elems = self.find_elements(selector)

        # Extend all the elements
        if elems:
            _elems = [WebRunnerElement(elem._parent, elem._id, elem._w3c) for elem in elems]
            return _elems
        else:
            raise NoSuchElementException 
Example #20
Source File: WebRunner.py    From PyWebRunner with MIT License 6 votes vote down vote up
def get_links(self, what='a'):
        '''
        Gets links by CSS selector or WebElement list.

        Parameters
        ----------
        what: str or list of WebElement
            A CSS selector to search for. This can be any valid CSS selector.
            -- or --
            A list of previously selected WebElement instances.

        Returns
        -------
        list of str
            A list of URL strings.

        '''
        elems = self._selector_or_elements(what)
        urls = []
        for elem in elems:
            href = elem.get_attribute('href')
            if href:
                urls.append(href)
        return urls 
Example #21
Source File: WebRunner.py    From PyWebRunner with MIT License 6 votes vote down vote up
def set_select_by_text(self, select, text):
        '''
        Set the selected value of a select element by the visible text.

        Parameters
        ----------
        select: str or selenium.webdriver.remote.webelement.WebElement
            Any valid CSS selector or a selenium element
        text: str
            The visible text in the select element option. (Not the value)

        '''
        if isinstance(select, str):
            elem = self.get_element(select)
        else:
            elem = select

        sel = Select(elem)
        sel.select_by_visible_text(text) 
Example #22
Source File: WebRunner.py    From PyWebRunner with MIT License 6 votes vote down vote up
def set_select_by_value(self, select, value):
        '''
        Set the selected value of a select element by the value.

        Parameters
        ----------
        select: str or selenium.webdriver.remote.webelement.WebElement
            Any valid CSS selector or a selenium element
        value: str
            The value on the select element option. (Not the visible text)

        '''
        if isinstance(select, str):
            elem = self.get_element(select)
        else:
            elem = select

        sel = Select(elem)
        sel.select_by_value(value) 
Example #23
Source File: listener.py    From robotframework-seleniumtestability with Apache License 2.0 5 votes vote down vote up
def after_change_value_of(self: "TestabilityListener", element: WebElement, driver: WebDriver) -> None:
        pass 
Example #24
Source File: find.py    From webium with Apache License 2.0 5 votes vote down vote up
def _validate_params(self):
        if self.by and not self.value:
            raise WebiumException('Provide search value in addition to by')
        if not self.by:
            if issubclass(self.ui_type, WebElement):
                raise WebiumException('Logical containers shouldn\'t be WebElement')
        else:
            if not issubclass(self.ui_type, WebElement):
                raise WebiumException('UI types should inherit WebElement') 
Example #25
Source File: driver_utils.py    From idom with MIT License 5 votes vote down vote up
def send_keys(element: WebElement, keys: Any) -> None:
    for char in keys:
        element.send_keys(char) 
Example #26
Source File: listener.py    From robotframework-seleniumtestability with Apache License 2.0 5 votes vote down vote up
def after_click(self: "TestabilityListener", element: WebElement, driver: WebDriver) -> None:
        pass 
Example #27
Source File: driver.py    From capybara.py with MIT License 5 votes vote down vote up
def _wrap_element_script_result(self, arg):
        if isinstance(arg, list):
            return [self._wrap_element_script_result(e) for e in arg]
        elif isinstance(arg, dict):
            return {k: self._wrap_element_script_result(v) for k, v in iter(arg.items())}
        elif isinstance(arg, WebElement):
            return Node(self, arg)
        else:
            return arg 
Example #28
Source File: listener.py    From robotframework-seleniumtestability with Apache License 2.0 5 votes vote down vote up
def before_change_value_of(self: "TestabilityListener", element: WebElement, driver: WebDriver) -> None:
        pass 
Example #29
Source File: element_operations.py    From warriorframework with Apache License 2.0 5 votes vote down vote up
def _get_element(self, element_or_browser, locator):
        """Get the element based on the provided input"""
        value = None
        if isinstance(element_or_browser, WebElement):
            value = element_or_browser
        else:
            value = EL.get_element(element_or_browser, locator)
        return value 
Example #30
Source File: click.py    From webium with Apache License 2.0 5 votes vote down vote up
def click(self, jquery=False):
        """
        Click by WebElement, if not, JQuery click
        """
        if jquery:
            e = JQuery(self)
            e.click()
        else:
            super(Clickable, self).click()