You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PyAutoGUI结合random模块实现随机坐标点击时的报错求助

使用PyAutoGUI结合random模块实现随机坐标点击时的报错求助

CODE BELOW!
It's kind of working, I'm using the 'print' function to check, but at the time the coordinates come inside () and between ''.

If anyone can help me, I would be grateful

import pyautogui as ac
from time import sleep
import random
import re

a1 = '431,263'
a2 = '498,268'
a3 = '555,258'
a4 = '621,257'
a5 = '683,258'
a6 = '419,315'
a7 = '494,320'
a8 = '560,316'
a9 = '613,313'
a10 = '679,325'
a11 = '433,382'
a12 = '478,378'
a13 = '547,389'
a14 = '609,389'
a15 = '694,394'
a16 = '439,454'
a17 = '496,449'
a18 = '562,457'
a19 = '617,454'
a20 = '678,449'
a21 = '433,514'
a22 = '487,512'
a23 = '556,510'
a24 = '627,520'
a25 = '673,513'

minas = a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25

alea = random.sample(minas, k=1)

ac.click(542,676)
sleep(1)
ac.click(alea)
#print(alea)

I waited for it to click, but it gave an error

我看了你的代码,问题出在两个关键地方:

  1. random.sample的返回值类型不符合要求:random.sample(minas, k=1)会返回一个包含单个元素的列表(比如['431,263']),而PyAutoGUI的click()函数需要的是两个整数参数(x、y坐标),或者一个包含两个整数的元组,直接传列表肯定会触发参数类型错误。
  2. 坐标是字符串格式,未转换为数值类型:你定义的每个坐标都是字符串(比如'431,263'),就算拿到单个字符串,直接传给click()也不行,因为函数无法识别字符串格式的坐标。

解决方案

你可以按以下步骤修改代码:

  1. 用random.choice()代替random.sample()——choice()会直接返回序列中的单个元素,而非列表,更适合你只选一个坐标的场景。
  2. 将选中的字符串坐标分割并转换为x、y两个整数,再传给click()。

修正后的完整代码

import pyautogui as ac
from time import sleep
import random
import re

a1 = '431,263'
a2 = '498,268'
a3 = '555,258'
a4 = '621,257'
a5 = '683,258'
a6 = '419,315'
a7 = '494,320'
a8 = '560,316'
a9 = '613,313'
a10 = '679,325'
a11 = '433,382'
a12 = '478,378'
a13 = '547,389'
a14 = '609,389'
a15 = '694,394'
a16 = '439,454'
a17 = '496,449'
a18 = '562,457'
a19 = '617,454'
a20 = '678,449'
a21 = '433,514'
a22 = '487,512'
a23 = '556,510'
a24 = '627,520'
a25 = '673,513'

minas = a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25

# 用random.choice获取单个坐标字符串
alea = random.choice(minas)
# 分割字符串并转换为整数
x, y = map(int, alea.split(','))

ac.click(542,676)
sleep(1)
# 传入整数坐标执行点击
ac.click(x, y)
# print(x, y)  # 现在print出来的就是纯整数坐标了

更简洁的优化方案

如果你想简化后续操作,一开始就把坐标定义成元组格式(比如a1 = (431,263)),这样后续只需要用random.choice()拿到元组直接传给click()就行,不用再做字符串分割转换:

# 示例:直接定义元组坐标
a1 = (431,263)
a2 = (498,268)
# ...其他坐标同理按元组格式定义

minas = a1, a2, ...  # 保持不变

alea = random.choice(minas)
ac.click(alea)  # 直接传元组即可完成点击

备注:内容来源于stack exchange,提问作者David Ferreira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 15:03:08