如何实现cookie.click()与自定义click()函数的同步执行?
需求:实现持续点击cookie达5分钟,同时每隔5秒检查价格条件并购买对应物品,但现有代码无法正常运行,尝试time.time()后仍未解决。
原代码:
count = 61 is_5_minutes = False minutes = 0 def click(): global minutes for sec in range(1, count): time.sleep(1) if sec == 60: click() minutes = +1 elif sec % 5 == 0: if current_price >= time_machine_price: time_machine.click() elif current_price >= portal_price: portal.click() elif current_price >= alchemy_lab_price: alchemy_lab.click() elif current_price >= shipment_price: shipment.click() elif current_price >= mine_price: mine.click() elif current_price >= factory_price: factory.click() elif current_price >= grandma_price: grandma.click() else: curser.click() while not is_5_minutes: cookie.click() click()
代码中的核心问题
- 递归调用导致栈溢出:当
sec == 60时递归调用click(),会不断创建函数栈帧,短时间内就会触发栈溢出错误;且minutes = +1是赋值而非累加,正确写法应为minutes += 1。 - 主线程被阻塞,无法持续点击cookie:
click()函数中的time.sleep(1)会阻塞主线程,导致主循环的cookie.click()只能在click()执行完毕后才会运行,完全违背“持续点击”的需求。 - 无终止条件触发:
is_5_minutes变量从未被设置为True,外层循环会无限运行。 - 变量作用域与实时性问题:
current_price等变量若未声明为全局或实时获取,无法在click()中访问;且游戏中current_price是动态变化的,不能用固定值判断。 - 拼写错误:
curser.click()应为cursor.click()。
修复后的代码
import time # 假设以下元素已通过网页自动化工具(如Selenium)正确定位 cookie = None cursor = None grandma_price = None factory_price = None mine_price = None shipment_price = None alchemy_lab_price = None portal_price = None time_machine_price = None def get_current_price(): # 实现从页面获取当前cookie数量的逻辑,示例: # return int(cookie_count_element.text.replace(',', '')) pass start_time = time.time() total_duration = 5 * 60 # 5分钟对应的秒数 last_check_timestamp = start_time while time.time() - start_time < total_duration: # 持续点击cookie cookie.click() # 每隔5秒执行一次购买检查 current_timestamp = time.time() if current_timestamp - last_check_timestamp >= 5: current_price = get_current_price() if current_price >= time_machine_price: time_machine.click() elif current_price >= portal_price: portal.click() elif current_price >= alchemy_lab_price: alchemy_lab.click() elif current_price >= shipment_price: shipment.click() elif current_price >= mine_price: mine.click() elif current_price >= factory_price: factory.click() elif current_price >= grandma_price: grandma.click() else: cursor.click() last_check_timestamp = current_timestamp
修复说明
- 用
time.time()记录开始时间,直接通过时间差判断是否达到5分钟,逻辑简洁且无递归风险。 - 主循环持续执行
cookie.click(),通过时间差而非time.sleep()触发购买检查,避免阻塞点击操作。 - 新增
get_current_price()函数,确保每次检查都获取最新的cookie数量。 - 修正拼写错误,移除无效递归调用,确保循环能正常终止。
内容的提问来源于stack exchange,提问作者Volturb
相关产品推荐
相关产品推荐

