1

I want to iterate through each radio button and perform some action. But enable to do so. It says selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document as error. The reason is after saving it reloads the page. How to handle it?

radioButton = (driver.find_elements_by_xpath("//input[@type='radio']"))
 
print(len(radioButton))
 
for radio in radioButton:
    print(radio.get_attribute("value"))
 
    radio.click()
 
    driver.find_element_by_xpath("//button[@ng-click='handleEdit()']").click()
 
    driver.find_element_by_xpath("//input[@placeholder='Contact Number']").clear()
 
    driver.find_element_by_xpath("//button[@ng-click='handleSave()']").click()
 
    time.sleep(5)
Frenchy
  • 16,386
  • 3
  • 16
  • 39
Piyush Singh
  • 21
  • 1
  • 4

2 Answers2

0

We face this stale element reference exception when the element we are interacting with is destroyed and then recreated again. When this happens the reference of the element in the DOM becomes stale. Hence we are not able to get the reference to the element.

How to handle StaleElementReferenceException

  1. Using Explicit Wait -- expected condition
  2. Using Try expect -- if use xpath in try then used a css select in the expect with StaleElement ReferenceException

Please refer to below articles --

https://www.softwaretestingmaterial.com/stale-element-reference-exception-selenium-webdriver/#:~:text=What%20is%20StaleElementReferenceException%20in%20Selenium,as%20a%20WebElement%20in%20WebDriver.

http://makeseleniumeasy.com/2018/12/02/ways-of-handling-staleelementreferenceexception-without-pagefactory/

https://darrellgrainger.blogspot.com/2012/06/staleelementexception.html

How to avoid "StaleElementReferenceException" in Selenium?

LearnerLaksh
  • 60
  • 1
  • 6
0

may be its outdated!

radioButton = (driver.find_elements_by_xpath("//input[@type='radio']"))
nbrbuts = len(radioButton)
print(len(radioButton))
for i in range(0, nbrbuts):
    radioButton = (driver.find_elements_by_xpath("//input[@type='radio']"))
    print(radioButton[i].get_attribute("value"))
    radioButton[i].click()
    time.sleep(1)
    driver.find_element_by_xpath("//button[@ng-click='handleEdit()']").click()
    driver.find_element_by_xpath("//input[@placeholder='Contact Number']").clear()
    driver.find_element_by_xpath("//button[@ng-click='handleSave()']").click()
    time.sleep(5)

with this error you have to reload each time your search

Frenchy
  • 16,386
  • 3
  • 16
  • 39