Python selenium.common.exceptions.StaleElementReferenceException() Examples

The following are 30 code examples of selenium.common.exceptions.StaleElementReferenceException(). 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.common.exceptions , 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: base.py    From tir with MIT License 6 votes vote down vote up
def get_element_value(self, element):
        """
        [Internal]

        Gets element value.

        :param element: Selenium element
        :type element: Selenium object

        :return: Element value
        :rtype: str

        Usage:

        >>> #Defining the element:
        >>> element = lambda: self.driver.find_element_by_id("example_id")
        >>> #Calling the method
        >>> text = self.get_element_value(element())
        """
        try:
            return self.driver.execute_script("return arguments[0].value", element)
        except StaleElementReferenceException:
            print("********Element Stale get_element_value*********")
            pass 
Example #3
Source File: tag_list.py    From pixelated-user-agent with GNU Affero General Public License v3.0 6 votes vote down vote up
def select_tag(context, tag):
    wait_for_user_alert_to_disapear(context)
    expand_side_nav(context)

    # try this multiple times as there are some race conditions
    try_again = 2
    success = False
    while (not success) and (try_again > 0):
        try:
            find_element_by_css_selector(context, '#tag-%s' % tag)

            e = find_element_by_css_selector(context, '#tag-%s .tag-label' % tag)
            e.click()

            find_element_by_css_selector(context, ".mail-list-entry__item[href*='%s']" % tag)
            success = True
        except (TimeoutException, StaleElementReferenceException):
            pass
        finally:
            try_again -= 1

    assert success 
Example #4
Source File: whatsapp_assistant_bot.py    From whatsapp-assistant-bot with MIT License 6 votes vote down vote up
def chat_history():
    text_bubbles = driver.find_elements_by_class_name("message-out")  # message-in = receiver, message-out = sender
    tmp_queue = []

    try:
        for bubble in text_bubbles:
            msg_texts = bubble.find_elements_by_class_name("copyable-text")
            for msg in msg_texts:
                tmp_queue.append(msg.text.lower())

        if len(tmp_queue) > 0:
            return tmp_queue[-1]  # Send last message in list

    except StaleElementReferenceException as e:
        print(str(e))
        # Something went wrong, either keep polling until it comes back or figure out alternative

    return False 
Example #5
Source File: helpers.py    From winnaker with MIT License 6 votes vote down vote up
def click_stubborn(driver, e, xpath):
    logging.debug("Starting stubborn clicks")
    MAX_ATTEMPT = 6
    attempt = 0
    while attempt < MAX_ATTEMPT:
        try:
            for i in range(10):
                attempt += 1
                e.click()
                break
            # breaks if no exception happens
            break
        except StaleElementReferenceException:
            a_nice_refresh(driver)
            e = wait_for_xpath_presence(driver, xpath)
        except WebDriverException:
            break
    return e 
Example #6
Source File: helpers.py    From winnaker with MIT License 6 votes vote down vote up
def get_body_text(driver,
        exponential_multiplier=cfg_wait_exponential_multiplier,
        exponential_max=cfg_wait_exponential_max,
        stop_max_attempt=cfg_retry_stop_max_attempt):
    @retry(
        wait_exponential_multiplier=exponential_multiplier,
        wait_exponential_max=exponential_max,
        stop_max_attempt_number=stop_max_attempt)
    def _get_body_text(driver):
        try:
            e = wait_for_xpath_presence(driver, "//body")
        except StaleElementReferenceException:
            a_nice_refresh(driver)
            e = wait_for_xpath_presence(driver, "//*")
            raise StaleElementReferenceException
        return e.get_attribute("outerHTML")
    return _get_body_text(driver)


# Subbornly clicks on the elements which run away from the DOM 
Example #7
Source File: webdriver.py    From avos with Apache License 2.0 6 votes vote down vote up
def __init__(self, parent, id_, locator, src_element, index=None):
        super(WebElementWrapper, self).__init__(parent, id_)
        self.locator = locator
        self.src_element = src_element

        # StaleElementReferenceException occurrence counter
        self.stale_reference_occurrence = 0

        # storing if web element reload succeed or not
        # in case of fail StaleElementReferenceException is raised
        self.reload_failed = False

        # in case element was looked up previously via find_elements
        # we need his position in the returned list
        self.index = index

        # if reloading of some other web element is in progress
        # StaleElementReferenceException is not raised within current context
        self.web_element_reload = False 
Example #8
Source File: tools.py    From Kairos with GNU General Public License v3.0 6 votes vote down vote up
def wait_for_element_is_stale(element):
    """
    If you keep some references to elements from the old page lying around, then they will become stale once the DOM refreshes, and stale elements cause selenium to raise a
    StaleElementReferenceException if you try and interact with them. So just poll one until you get an error. Bulletproof!
    @see http://www.obeythetestinggoat.com/how-to-get-selenium-to-wait-for-page-load-after-a-click.html
    :param element:
    :return:
    """
    # link = browser.find_element_by_link_text('my link')
    # link.click()

    def has_gone_stale():
        try:
            # poll the link with an arbitrary call
            value = element.text
            # always return false and fool PyCharm check of unused var 'value'
            return value == "" and value != ""
        except StaleElementReferenceException:
            return True

    wait_for(has_gone_stale) 
Example #9
Source File: test_find_all.py    From selenium-python-helium with MIT License 6 votes vote down vote up
def test_interact_with_found_elements(self):
		all_tfs = find_all(TextField())
		example_tf = None
		for text_field in all_tfs:
			try:
				id_ = text_field.web_element.get_attribute('id')
			except StaleElementReferenceException:
				# This may happen for found web elements in different iframes.
				# TODO: Improve this, eg. by adding a .getId() property to
				# TextField (/HTMLElement) which handles this problem.
				pass
			else:
				if id_ == 'exampleTextFieldId':
					example_tf = text_field
		self.assertIsNotNone(example_tf)
		write("test_interact_with_found_elements", into=example_tf)
		self.assertEqual(
			"test_interact_with_found_elements",
			TextField("Example Text Field").value
		) 
Example #10
Source File: base.py    From tir with MIT License 6 votes vote down vote up
def set_element_focus(self, element):
        """
        [Internal]

        Sets focus on element.

        :param element: Selenium element
        :type element: Selenium object

        Usage:

        >>> #Defining the element:
        >>> element = lambda: self.driver.find_element_by_id("example_id")
        >>> #Calling the method
        >>> text = self.set_element_focus(element())
        """   
        try:
            self.driver.execute_script("window.focus(); arguments[0].focus();", element)
        except StaleElementReferenceException:
            print("********Element Stale set_element_focus*********")
            pass 
Example #11
Source File: base.py    From tir with MIT License 6 votes vote down vote up
def scroll_to_element(self, element):
        """
        [Internal]

        Scroll to element on the screen.

        :param element: Selenium element
        :type element: Selenium object

        Usage:

        >>> #Defining an element:
        >>> element = lambda: self.driver.find_element_by_id("example_id")
        >>> #Calling the method
        >>> self.scroll_to_element(element())
        """
        try:
            if element.get_attribute("id"):
                self.driver.execute_script("return document.getElementById('{}').scrollIntoView();".format(element.get_attribute("id")))
            else:
                self.driver.execute_script("return arguments[0].scrollIntoView();", element)
        except StaleElementReferenceException:
            print("********Element Stale scroll_to_element*********")
            pass 
Example #12
Source File: base.py    From tir with MIT License 6 votes vote down vote up
def get_element_text(self, element):
        """
        [Internal]

        Gets element text.

        :param element: Selenium element
        :type element: Selenium object

        :return: Element text
        :rtype: str

        Usage:

        >>> #Defining the element:
        >>> element = lambda: self.driver.find_element_by_id("example_id")
        >>> #Calling the method
        >>> text = self.get_element_text(element())
        """
        try:
            return self.driver.execute_script("return arguments[0].innerText", element)
        except StaleElementReferenceException:
            print("********Element Stale get_element_text*********")
            pass 
Example #13
Source File: element_locator_tests.py    From nerodia with MIT License 6 votes vote down vote up
def test_raises_exception_if_element_continues_to_go_stale(self, mocker, browser_mock, driver_mock):
        browser_mock.wd = driver_mock
        el = wd_element(mocker)
        locator = {'xpath': './/div', 'id': 'foo'}
        mtcher = matcher(mocker, browser_mock, locator)
        expect_all(driver_mock, [el])
        mtcher.match.side_effect = [StaleElementReferenceException()] * 3

        message_parts = ['Unable to locate element from',
                         "'xpath': './/div'",
                         "'id': 'foo'",
                         'due to changing page']

        with pytest.raises(LocatorException) as e:
            locate_one(mtcher, locator)
        assert all(part in e.value.args[0] for part in message_parts) 
Example #14
Source File: webdriver.py    From poium with Apache License 2.0 6 votes vote down vote up
def refresh_element(self, elem, timeout=10):
        """
        selenium API
        Refreshes the current page, retrieve elements.
        """
        warnings.warn("use driver.elem.refresh_element() instead",
                      DeprecationWarning, stacklevel=2)
        try:
            timeout_int = int(timeout)
        except TypeError:
            raise ValueError("Type 'timeout' error, must be type int() ")

        for i in range(timeout_int):
            if elem is not None:
                try:
                    elem
                except StaleElementReferenceException:
                    self.driver.refresh()
                else:
                    break
            else:
                sleep(1)
        else:
            raise TimeoutError("stale element reference: element is not attached to the page document.") 
Example #15
Source File: page_objects.py    From poium with Apache License 2.0 6 votes vote down vote up
def refresh_element(self, timeout=10):
        """
        selenium API
        Refreshes the current page, retrieve elements.
        """
        try:
            timeout_int = int(timeout)
        except TypeError:
            raise ValueError("Type 'timeout' error, must be type int() ")

        elem = self.__get_element(self.k, self.v)
        for i in range(timeout_int):
            if elem is not None:
                try:
                    elem
                except StaleElementReferenceException:
                    Browser.driver.refresh()
                else:
                    break
            else:
                sleep(1)
        else:
            raise TimeoutError("stale element reference: element is not attached to the page document.") 
Example #16
Source File: element_locator_tests.py    From nerodia with MIT License 6 votes vote down vote up
def test_raises_locator_exception_if_element_continues_to_go_stale(self, mocker, browser_mock, driver_mock):
        browser_mock.wd = driver_mock
        el = wd_element(mocker)
        locator = {'xpath': './/div', 'id': 'foo'}
        mtcher = matcher(mocker, browser_mock, locator)
        expect_all(driver_mock, [el])
        mtcher.match.side_effect = [StaleElementReferenceException()] * 3

        message_parts = ['Unable to locate element collection from',
                         "'xpath': './/div'",
                         "'id': 'foo'",
                         'due to changing page']

        with pytest.raises(LocatorException) as e:
            locate_all(mtcher, locator)
        assert all(part in e.value.args[0] for part in message_parts) 
Example #17
Source File: element_collection.py    From nerodia with MIT License 6 votes vote down vote up
def _elements_with_tags(self):
        els = self._elements
        if 'tag_name' in self.selector:
            return [(e, self.selector['tag_name']) for e in els]
        else:
            retries = 0
            while retries <= 2:
                try:
                    return zip(els, self._execute_js('getElementTags', els))
                except StaleElementReferenceException:
                    retries += 1
                    sleep(0.5)
                    pass

        raise LocatorException('Unable to locate element collection from {} due to changing '
                               'page'.format(self.selector)) 
Example #18
Source File: scanner.py    From traxss with MIT License 6 votes vote down vote up
def html_scanner(self, payload, webelement_list, target_url):
        for id in webelement_list:
            try:
                if id.tag_name == 'textarea' or id.tag_name == 'input':
                    id.send_keys(payload)
                    WebDriverWait(self.driver, 1).until(expected_conditions.alert_is_present())
                    self.driver.switch_to.alert.accept()
                    if self.count_results(self.raw_params, target_url, "HTML Injection"):
                        self.driver.quit()
                        self.final_report()
                if id.tag_name == 'button' or id.tag_name == 'input':
                    id.click()
                    WebDriverWait(self.driver, 1).until(expected_conditions.alert_is_present())
                    self.driver.switch_to.alert.accept()
                    if self.count_results(self.raw_params, target_url, "HTML Injection"):
                        self.driver.quit()
                        self.final_report()
            except TimeoutException:
                pass
            except StaleElementReferenceException:
                pass
            except ElementNotInteractableException:
                pass 
Example #19
Source File: driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def _expected_condition_find_element_not_containing_text(self, element_text_pair):
        """Tries to find the element and checks that it does not contain the specified text,
            but does not thrown an exception if the element is 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 not be contained into the element
        :returns: the web element if it does not contain 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 not in web_element.text else False
        except StaleElementReferenceException:
            return False 
Example #20
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 #21
Source File: scrape_lib.py    From finance-dl with GNU General Public License v2.0 5 votes vote down vote up
def is_displayed(element):
    """Returns `True` if `element` is displayed.

    Ignores StaleElementReferenceException.
    """

    try:
        return element.is_displayed()
    except StaleElementReferenceException:
        return False 
Example #22
Source File: helpers.py    From selenium_extensions with MIT License 5 votes vote down vote up
def element_has_gone_stale(element):
    '''Checks if element has gone stale

    Args:
        element (selenium.webdriver.remote.webelement.WebElement): Selenium webelement to check for.

    Returns:
        bool: True if element has gone stale, False otherwise.

    Examples:
        ::

            from selenium_extensions.helpers import element_has_gone_stale


            if element_has_gone_stale(your_element):
                pass  # Do something

        ::

            from selenium_extensions.helpers import wait_for_function_truth
            from selenium_extensions.helpers import element_has_gone_stale


            login_btn = driver.find_element_by_class_name('login_btn')
            wait_for_function_truth(element_has_gone_stale, element)
    '''
    try:
        # Poll the object with an arbitrary call
        element.find_elements_by_id('non-existing-id')
        return False
    except StaleElementReferenceException:
        return True 
Example #23
Source File: netgear_crawler2.py    From DLink_Harvester with GNU General Public License v3.0 5 votes vote down vote up
def getElemText(self: WebElement, timeOut: float=60.0, pollFreq=3.0) -> str:
    while (time.time()-begin) < timeOut:
        try:
            return self.text.strip()
        except StaleElementReferenceException:
            time.sleep(pollFreq)
    raise TimeoutException("[getElemText] elem=%s"%WebElement) 
Example #24
Source File: netgear_crawler2.py    From DLink_Harvester with GNU General Public License v3.0 5 votes vote down vote up
def waitText(self, css: str,timeOut: float=60, pollFreq: float=3.0) -> str:
    begin = time.time()
    while (time.time()-begin) < timeOut:
        try:
            return self.waitVisible(css, pollFreq).text
        except (TimeoutException, StaleElementReferenceException):
            time.sleep(pollFreq)
            timeElapsed += (time.time()-beginTime)
            continue
        except Exception as ex:
            print(ex)
            return None
    return None 
Example #25
Source File: conditions.py    From behave-webdriver with MIT License 5 votes vote down vote up
def __call__(self, *args, **kwargs):
        try:
            result = super(NegationMixin, self).__call__(*args, **kwargs)
        except StaleElementReferenceException:
            return False  # Stale elements are unreliable, always try to regrab the element
        if self.negative:
            return not result
        return result 
Example #26
Source File: conditions.py    From behave-webdriver with MIT License 5 votes vote down vote up
def __call__(self, driver):
        try:
            element = driver.find_element(*self.locator)
        except StaleElementReferenceException:
            return False
        result = element.is_enabled()
        if self.negative:
            return not result
        return result 
Example #27
Source File: conditions.py    From behave-webdriver with MIT License 5 votes vote down vote up
def __call__(self, driver):
        """
        Same logic as in EC.text_to_be_present_in_element except StaleElementReferenceException is not caught
        this, for now, is needed to distinguish if a False return value is the result of this exception.
        """
        try:
            element = driver.find_element(*self.locator)
            result = bool(element.text)
        except StaleElementReferenceException:
            return False

        if self.negative:
            return not result
        return result 
Example #28
Source File: videos.py    From echo360 with MIT License 5 votes vote down vote up
def _loop_find_m3u8_url(self, video_url, waitsecond=15, max_attempts=5):
        stale_attempt = 1
        refresh_attempt = 1
        while True:
            self._driver.get(video_url)
            try:
                # wait for maximum second before timeout
                WebDriverWait(self._driver, waitsecond).until(
                    EC.presence_of_element_located((By.ID, "content-player")))
                return self._driver.find_element_by_id(
                    'content-player').find_element_by_tag_name(
                        'video').get_attribute('src')
            except selenium.common.exceptions.TimeoutException:
                if refresh_attempt >= max_attempts:
                    print(
                        '\r\nERROR: Connection timeouted after {} second for {} attempts... \
                          Possibly internet problem?'.format(
                            waitsecond, max_attempts))
                    raise
                refresh_attempt += 1
            except StaleElementReferenceException:
                if stale_attempt >= max_attempts:
                    print(
                        '\r\nERROR: Elements are not stable to retrieve after {} attempts... \
                        Possibly internet problem?'.format(max_attempts))
                    raise
                stale_attempt += 1 
Example #29
Source File: element_locator_tests.py    From nerodia with MIT License 5 votes vote down vote up
def test_relocates_if_element_goes_stale(self, mocker, browser_mock, driver_mock):
        browser_mock.wd = driver_mock
        el = wd_element(mocker)
        locator = {'xpath': './/div', 'id': 'foo'}
        mtcher = matcher(mocker, browser_mock, locator)
        expect_all(driver_mock, [el])
        mtcher.match.side_effect = [StaleElementReferenceException(), el]

        assert locate_one(mtcher, locator) == el 
Example #30
Source File: collections_tests.py    From nerodia with MIT License 5 votes vote down vote up
def test_raises_exception_if_any_element_in_collection_continues_to_go_stale(browser, mocker):
    mock = mocker.patch('selenium.webdriver.remote.webdriver.WebDriver.execute_script')
    mock.side_effect = [StaleElementReferenceException()] * 3
    message_parts = [
        'Unable to locate element collection from',
        "'xpath': './/span'",
        'due to changing page'
    ]

    with pytest.raises(LocatorException) as e:
        list(browser.span().elements(xpath='.//span'))
    assert all(part in e.value.args[0] for part in message_parts)