循环中的动作链仅工作一次(Selenium/Python)

2024-04-01

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 https://orteil.dashnet.org/cookieclicker/. 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


您在这里要做的就是给枪装一次子弹,然后循环按下扳机几次...... 要执行您希望的操作,您应该稍微更改您的代码,如下所示:

actions = ActionChains(driver)

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

顺便说一句,我想这个代码仍然无法工作,因为第一次点击后cookie元素,即使它会再次出现,它也将是一个新的、另一个元素,即使它可以使用相同的定位器定位。
所以尝试再次单击它会导致StaleElementReferenceException.
为了使这项工作正常进行,您必须找到cookie每次再次元素,如下:

actions = ActionChains(driver)

for i in range(4000):
    cookie = wait.until(EC.visibility_of_element_located((By.ID, "bigCookie")))
    actions.click(cookie)
    actions.perform()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

循环中的动作链仅工作一次(Selenium/Python) 的相关文章

随机推荐