Reputation: 94
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)
Upvotes: 0
Views: 646
Reputation: 4829
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
Upvotes: 1