0

I am trying to run a code and every time, I am getting an error of "StaleElementReferenceException", and it makes my life a living hell. The code is as follow:

import time
import unittest
import DropDownAddresses
import re


from selenium import webdriver
from selenium.common.exceptions import *
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import *

UserEmail = "[email protected]"
UserPassword = '12345678'
SubcategoryName = input("Enter Name of Sub category: ")


def dropDown(self, Category):
    driver = self.driver
    actions = ActionChains ( driver )
    actions.move_to_element ( Category ).perform ( )
    SelectedCategory = driver.find_element_by_partial_link_text ( SubcategoryName )
    self.NameofSelectedCategory = print ( SelectedCategory.text )
    time.sleep ( 2 )
    actions.move_to_element ( SelectedCategory ).click ( ).perform ( )
    time.sleep ( 2 )


def headings(self):
    driver= self.driver
    Pageheading = driver.find_element_by_tag_name ( "h1" ).text
    headingName = re.sub ( "[^a-zA-Z]", "", Pageheading )
    # Mainheading = int(Pageheading.text[:-4])
    offerCount = re.findall ( '\d+', Pageheading )

    NumberofOffers = (offerCount[0])
    if headingName == self.NameofSelectedCategory:
        print ( "Heading is correct i.e. " + headingName )
    else:

        print ( "Heading was not correct" )

    if NumberofOffers == 1:
        print ( "Number of Offers in this section is " + str ( NumberofOffers ) )
    else:
        print ( "Number of offers in this section are " + str ( NumberofOffers ) )



class Categories(unittest.TestCase):
    def setUp(self):
        DropDownAddresses.browserCalling(self)

    def test_Test1(self):
        DropDownAddresses.openBrowser(self)
        driver = self.driver
        MoveSliderAhead = driver.find_element_by_xpath("//*[@id='wrapper']/div[2]/div[1]//div/button[2]")
        MoveSliderAhead.click()
        time.sleep(2)
        print("Slider Moved Ahead")

        MoveSliderBehind = driver.find_element_by_xpath("//*[@id='wrapper']/div[2]/div[1]//div/button[1]")
        MoveSliderBehind.click()
        time.sleep(2)
        print("Slider Moved Behind")


        HealthandBeautyDD = driver.find_element_by_xpath("//*[@id='bs-example-navbar-collapse-1']/ul/li[1]/a")
        SportsnLeisureDD= driver.find_element_by_xpath("//*[@id='bs-example-navbar-collapse-1']/ul/li[2]/a")
        FashionDD = driver.find_element_by_xpath("//*[@id='bs-example-navbar-collapse-1']/ul/li[3]/a")
        JewellWatchDD = driver.find_element_by_xpath("//*[@id='bs-example-navbar-collapse-1']/ul/li[4]/a")
        ElectronicsDD = driver.find_element_by_xpath("//*[@id='bs-example-navbar-collapse-1']/ul/li[5]/a")


        dropDown(self, HealthandBeautyDD )
        headings(self)

        Wait = WebDriverWait ( driver, 10, poll_frequency=1,
                               ignored_exceptions=[NoSuchElementException, ElementNotVisibleException] )
        Wait.until ( EC.element_to_be_clickable((By.XPATH, "//*[@id='bs-example-navbar-collapse-1']/ul/li[5]/a")))

        time.sleep(3)
        dropDown(self, ElectronicsDD)
        headings(self)







    def tearDown(self):
        print("Checking Categories")

if __name__ == "__main__":

Whereas DropDownAddresses file is as like this:

import os
import time
import unittest


from selenium import webdriver
from selenium.common.exceptions import *
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait

UserEmail = "[email protected]"
UserPassword = '12345678'


def browserCalling(self):
    driverlocation = "/Users/new/Documents/Learning/Drivers/selenium-2.53.1/py/selenium/webdriver/chromedriver"
    os.environ["webdriver.chrome.driver"] = driverlocation
    self.driver = webdriver.Chrome ( driverlocation )


def openBrowser(self):
    driver = self.driver
    url = "https://bizplace.theentertainerme.com/"
    driver.get ( url )
    driver.implicitly_wait ( 10 )
    self.LoginButton = driver.find_element_by_id ( "signin" )
    self.LoginButton.click ( )
    self.LoginEmail = driver.find_element_by_xpath ( "//*[@id='sign_form-default']//div[1]/input[@type='email']" )
    self.LoginEmail.clear ( )
    self.LoginEmail.click ( )
    self.LoginEmail.send_keys ( UserEmail )

    self.LoginPassword = driver.find_element_by_xpath (
        "//*[@id='sign_form-default']//div[1]/input[@type='password']" )
    self.LoginPassword.clear ( )
    self.LoginPassword.click ( )
    self.LoginPassword.send_keys ( UserPassword )

    self.LoginSubmitButton = driver.find_element_by_xpath ( "//*[@id='sign_form-default']//div[3]/input" )
    self.LoginSubmitButton.click ( )
    time.sleep ( 5 )

Now the Problem is, After done processes on "Health and Beauty" dropdown, I want to switch to "Electronics" dropdown and it's showing me the following error:

Error
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/case.py", line 58, in testPartExecutor
    yield
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/case.py", line 600, in run
    testMethod()
  File "/Users/new/PycharmProjects/Selenium/Categories.py", line 87, in test_Test1
    dropDown(self, ElectronicsDD)
  File "/Users/new/PycharmProjects/Selenium/Categories.py", line 25, in dropDown
    actions.move_to_element ( Category ).perform ( )
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/common/action_chains.py", line 83, in perform
    action()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/common/action_chains.py", line 293, in <lambda>
    Command.MOVE_TO, {'element': to_element.id}))
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=63.0.3239.84)
  (Driver info: chromedriver=2.33.506106 (8a06c39c4582fbfbab6966dbb1c38a9173bfb1a2),platform=Mac OS X 10.13.0 x86_64)




Ran 1 test in 47.314s

FAILED (errors=1)

Process finished with exit code 1

Can someone please help me out on this?

2

1 Answer 1

2

StaleElementReferenceException happens because you went away from a page where you did find the element. For example:

element = driver.find_element_by_css_selector('#menu')
element.click()
element.click()

We got StaleElementReferenceException

But if:

element = driver.find_element_by_css_selector('#menu')
element.click()
element = driver.find_element_by_css_selector('#menu')
element.click()

Every thing will be fine.

You should redesign your test. Try to find an element just before making an action:

ElectronicsDD = driver.find_element_by_xpath("//*[@id='bs-example-navbar-collapse-1']/ul/li[5]/a")
dropDown(self, ElectronicsDD)
Sign up to request clarification or add additional context in comments.

1 Comment

It Worked.. Thanks alot Mate :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.