How to execute ActionChains multiple times Selenium

Viewed 30

I have made a simple Selenium script which visits a webpage and clicks the cookie. But I have only managed to get it to click once even though I have put it in a loop. Can anyone tell me where I am going wrong?

http://orteil.dashnet.org/cookieclicker/

from selenium import webdriver
import os
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.common.action_chains import ActionChains
import time

os.environ['PATH'] = r"C:\Users\Ruibin\Desktop\Python\chromedriver_win32"

driver = webdriver.Chrome()
driver.get('https://orteil.dashnet.org/cookieclicker/')


try:
    WebDriverWait(driver, 5).until(
        EC.presence_of_element_located(
            (By.ID, 'langSelect-EN')
        )
    )
    driver.find_element(By.ID, 'langSelect-EN').click()

finally:

    driver.implicitly_wait(10)
    cookies = driver.find_element(By.ID, 'bigCookie')
    cookie_count = driver.find_element(By.ID, 'cookies')

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

    for i in range(10):
        actions.perform()
1 Answers

For clicking the cookie element in a loop you have to get that element in a loop each time since after each click that element becomes stale.
Also you need to define the action itself each time again in a loop.
This code works:

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("--start-maximized")

s = Service('C:\webdrivers\chromedriver.exe')

driver = webdriver.Chrome(options=options, service=s)

url = 'https://orteil.dashnet.org/cookieclicker/'

wait = WebDriverWait(driver, 10)
driver.get(url)
try:
   wait.until(EC.element_to_be_clickable((By.ID, 'langSelect-EN'))).click()

finally:

    cookies = wait.until(EC.element_to_be_clickable((By.ID, 'bigCookie')))
    cookie_count = wait.until(EC.element_to_be_clickable((By.ID, 'cookies')))

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

    for i in range(10):
        cookies = wait.until(EC.element_to_be_clickable((By.ID, 'bigCookie')))
        actions.click(cookies)
        actions.perform()

Also instead of presence_of_element_located you should always use element_to_be_clickable in case you want to click that element.
Also it is much better to use element_to_be_clickable or visibility_of_element_located instead of implicitly_wait

Related