Search code examples
pythonseleniumloopsautomation

Action Chain in loop works only once(Selenium/Python)


I'm trying to implement a cookie clicker bot. Cookie clicker it's just a stupid simple game, where you can click on the cookie to earn more cookies. You can take a look at that masterpiece here. The bot should just open the page, and click on the cookie 4000 times, but it clicks only one time.

import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait    
from selenium.webdriver.common.action_chains import ActionChains

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://orteil.dashnet.org/cookieclicker/")

driver.implicitly_wait(10)

cookie = driver.find_element(By.ID, "bigCookie")

actions = ActionChains(driver)
actions.click(cookie)

for i in range(4000):
    actions.perform()

I see these messages in the console. What is wrong with me my code? errors


Solution

  • What you trying to do here is to load the gun one time and then to press on trigger several times in a loop... To do what you wish you should slightly change your code as following:

    actions = ActionChains(driver)
    
    for i in range(4000):
        actions.click(cookie)
        actions.perform()
    

    BTW I guess this code will still not work since after the first click on the cookie element even if it will appear again it will be a NEW, ANOTHER element even if it could be located with the same locator.
    So trying to click it again will cause StaleElementReferenceException.
    To make this work you will have to locate the cookie element again each time, as following:

    actions = ActionChains(driver)
    
    for i in range(4000):
        cookie = wait.until(EC.visibility_of_element_located((By.ID, "bigCookie")))
        actions.click(cookie)
        actions.perform()