Selenium Python - Unable to find an element, get stale element exception when using element locator

  • Scenario: 1.Login to a website using script and navigate to the Home page. 2. On the home page, click a link and navigate to a new page. 3. Then navigate back to the home page using the top navigation bar Home link.

    I am using the POM ( Page object model) where all my locators are defined in one python module.

    The following is my directory structure 1. ( This is where I specify all the login credentials, web driver and base url).

    1. This has setup and tear down methods)

    2. ( This contains the locators for each page under a Locator class)

    3. Page objects( Under this directory I have for the home page that has methods under the Homepage class, each of these methods returns a specific web element locator using the Locator class)

    4. test scripts(, this is where I am extending my Envsetup class to run the tests.

    When I try to navigate back to my Home page, I get a stale elementrefernce exception error.

    class Home(EnvSetup):
        def test_HomePage(self):
            browser = self.browser
            homepage = Home(browser)
            assert browser.title
            print('Running tests on ' + browser.title)
            if homepage.view_all_users().is_displayed(): # This method is defined in the Hompage module
                raise NoSuchElementException
            #browser.find_element_by_xpath('//*[@id="home"]').click() -----------> This works fine, takes me back to the Home page
        if homepage.nav_to_home().is_displayed(): ----------> I get a StaleElementException error
     In the following case, I get 
    webDriverWait(browser, 20).until(EC.presence_of_element_located(By.XPATH, homepage.nav_to_home()))
    TypeError: __init__() takes 2 positional arguments but 3 were given
                WebDriverWait(browser, 20).until(EC.presence_of_element_located(By.XPATH, homepage.nav_to_home()))
            except StaleElementReferenceException as e:
                raise e
    if __name__ == '__main__':

    from Tests.Pageobjects.Locators import Locator
    from import By
    class Home(object):
        def __init__(self, browser):
            self.browser = browser
            self.logo = browser.find_element(By.XPATH, Locator.logo)
            self.nav_Home = browser.find_element(By.XPATH, Locator.nav_Home)
        def get_logo(self):
            return self.logo
        def nav_to_home(self):
            return self.nav_Home

  • Fixed the Stale element exception with used WebDriverwait in my Page object. Added WebDriverwait(self.browser, 100).until(lambda browser: self.browser.find_element(By.XPATH, Locator.nav_Home) to my methods that return the locators in the page object.


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2