Selenium two consecutive explicit wait times and clicks creates error with finding same elements on new page

Viewed 32

While I was trying to create a bot to automate shopping on a certain page, I run into a problem that I couldn't fix for a long time. The goal of program was to enter the page, click on the certain button representing size and click on the buy button to add item to a cart. It was running in a loop for every link to the item that I've supplied. The code of the program:

def buy(driver: webdriver, href: str):
  driver.get(href)
  sizeButton = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, f"//span[contains(text(),'{size.upper()}')]/../..")))
  sizeButton.click()
  buyButton = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, "//div[@id='addToCartButton']/button")))
  buyButton.click()

The code worked on the first iteration, but after adding first item to a cart and switching to next page, driver couldn't find the same WebElements. I made sure that XPaths didn't change, new page was on the same window and there were no any extra iframes. To addition to that, when the code didn't include one of the "clicks" on either button, code worked fine.

After trying many possible fixes, accidentally I run into solution by doing both explicit waits first and then forcing click methods.

def buy(driver: webdriver, href: str):
  driver.get(href)
  sizeButton = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, f"//span[contains(text(),'{size.upper()}')]/../..")))
  buyButton = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, "//div[@id='addToCartButton']/button")))
  sizeButton.click()
  buyButton.click()

Is there anyone who can explain me why earlier approach didn't work? I had lost a lot of time fixing it, so I would love to gain new knowledge to avoid mistakes in the future.

0 Answers
Related