0

I am trying to click on all the products from this link. I wanted to click on all the products(click on the first product, come back, click on the second product, and so forth till the last product). But as soon as the loop reaches the second product, I get a stale element not found error. I've tried implicit wait, time. sleep. I couldn't solve it. Any help would be appreciated

import time
from selenium import webdriver
from selenium.common import StaleElementReferenceException
from selenium.webdriver.common.by import By

chrome_options = webdriver.ChromeOptions()

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://foodkoreadubai.com/collections/beverages")
time.sleep(10)
try:
    popup_element = driver.find_element(By.CLASS_NAME, "popup-close")
    close_button = popup_element.find_element(By.CSS_SELECTOR, ".icon-close")
    close_button.click()
    time.sleep(4)
except StaleElementReferenceException:
    print("Pop up did not pop up")
finally:
    box_product_elements = driver.find_elements(By.CSS_SELECTOR, ".box.product")
    i = 1
    last_product = len(box_product_elements)
    while i < last_product:
        box_product_elements[i].click()
        driver.back()
        i += 1
        time.sleep(2)
  • 1
    stale element exception occurs when the page got refreshed, so that time element get missed from the desired location, so in that time you handle with webdriver wait and use the method of in invisiblelocator. – Bhairu Aug 11 '23 at 08:11

1 Answers1

1

You got StaleElementReferenceException, because you clicked driver.back() and page with product is re-rendered, so previous WebElements instances don't exist anymore on newly rendered page.

You need to get elements array again to handle this.

# your code

box_product_elements = driver.find_elements(By.CSS_SELECTOR, ".box.product")
i = 1
last_product = len(box_product_elements)
while i < last_product:
    driver.find_elements(By.CSS_SELECTOR, ".box.product")[i].click()
    driver.back()
    i+=1
Yaroslavm
  • 1,762
  • 2
  • 7
  • 15