I am looking to make a script to look for a specific class and select all elements that are assigned this class. I want it to click on each of these elements and when done to go to another page. It needs to run in a loop so if the elements have not been found then to refresh until found. It seems to do a good job at selecting all of these elements one by one if they are present but gets stuck on what to do after. If no elements are on the page then it does not refresh and continues with the code outside of the loop. I am really unsure on how to code this so I will be grateful for any help.
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.maximize_window()
driver.get('https://www.masterofmalt.com/distilleries/ben-nevis-whisky-distillery/')
driver.implicitly_wait(5)
cookies_button = driver.find_element(By.ID, "onetrust-accept-btn-handler").click()
buybutton = driver.find_elements(By.CLASS_NAME, "mom-btn-buy-add-to-basket")
while(True):
try:
for x in range(0, len(buybutton)):
if buybutton[x].is_displayed():
buybutton[x].click()
print("add button clicked")
time.sleep(2)
except:
driver.refresh()
Appreciate any input into this as I am stuck.
Many thanks
This code
while(True)
is an infinite loop, I would suggest to avoid it.Try to work with the total number of elements found.
I don't think using
while
instead offor
is a good idea.