I have added implicit wait in my code and it results in error "Message: stale element reference: element is not attached to the page document"
Below is the code
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
service_obj = Service("C:/Users/divya/Downloads/chromedriver_win32/chromedriver.exe")
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(service=service_obj)
driver.implicitly_wait(5)
driver.get("https://rahulshettyacademy.com/seleniumPractise/#/")
driver.find_element(By.CSS_SELECTOR, ".search-keyword").send_keys("ber")
# time.sleep(2)
products = driver.find_elements(By.XPATH, "//div[@class='products']/div")
count = len(products)
assert count > 0
for product in products:
product.find_element(By.XPATH, "div/button").click() #=======ERROR HERE=============
driver.find_element(By.CSS_SELECTOR, ".cart-icon").click()
driver.find_element(By.XPATH, "//button[text()='PROCEED TO CHECKOUT']").click()
# time.sleep(3)
driver.find_element(By.XPATH, "//input[@type='text']").send_keys("rahulshettyacademy")
driver.find_element(By.CSS_SELECTOR, ".promoBtn").click()
Sleep() functions work fine instead of implicit waits.
Anyone having suggestion/reason for the same. Please guide
CodePudding user response:
I think that problem is because the page is being refreshing or the element is being deleting from the DOM after it is located, but before it is clicked
To solve it I suggest
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
...
for product in products:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "div/button"))
)
element.click()
...
and remove
driver.implicitly_wait(5)
CodePudding user response:
You need to wait for some time after searching:
driver.get("https://rahulshettyacademy.com/seleniumPractise/#/")
driver.find_element(By.CSS_SELECTOR, ".search-keyword").send_keys("ber")
time.sleep(1)
products = driver.find_elements(By.XPATH, "//div[@class='products']/div")
count = len(products)
assert count > 0
i = 0
for i in range(len(products)):
driver.find_element(By.XPATH, "(//div[@class='products']//button)[" str(i 1) "]").click()
driver.find_element(By.CSS_SELECTOR, ".cart-icon").click()
driver.find_element(By.XPATH, "//button[text()='PROCEED TO CHECKOUT']").click()
time.sleep(1)
driver.find_element(By.XPATH, "//input[@type='text']").send_keys("rahulshettyacademy")
driver.find_element(By.CSS_SELECTOR, ".promoBtn").click()