因此,当我需要更改代码中以下代码的位置时,我正在编辑我的大型自动化脚本。将代码放在脚本的上部位置后,我突然开始收到以下错误:
File "C:\Users\User\Desktop\clicker.py", line 198, in <module>
while a[i] != None:
IndexError: list index out of range
我尝试检查索引,但它们似乎没问题。我不知道如何进一步调试它。奇怪的是,错误显示在 while 循环的末尾(如果它仅在开始时显示,我知道如何修复它)。这意味着列表中的每个检测到的坐标都会被执行,并且当没有更多坐标存在时它会在最后失败。我的代码是:
# convert broken xls to working xlsx
pyautogui.click(x=75, y=746)
sleep(1)
pyautogui.click(pyautogui.locateCenterOnScreen('C:/Users/User/Documents/Clicker/downloads.png'))
sleep(3)
a = list(pyautogui.locateAllOnScreen('C:/Users/User/Documents/Clicker/excel.png'))
i=0
while a[i] != None:
x, y = pyautogui.center(a[i])
pyautogui.click(x, y, clicks=2)
sleep(4)
pyautogui.click(pyautogui.locateCenterOnScreen('C:/Users/User/Documents/Clicker/yes.png'))
sleep(2.5)
try:
pyautogui.click(pyautogui.locateCenterOnScreen('C:/Users/User/Documents/Clicker/editing.png'))
except TypeError:
print("No need to press editing mode")
# click file
pyautogui.click(x=29, y=50)
sleep(1)
# click save as
pyautogui.click(x=50, y=312)
sleep(1)
# click on drop down menu
pyautogui.click(x=814, y=177)
sleep(2)
# select .xlsx
pyautogui.click(x=814, y=200)
sleep(1)
# click save
pyautogui.click(x=920, y=170)
sleep(2)
# close excel
pyautogui.click(x=997, y=14)
sleep(2)
i+=1
#-----EXCEL------------
最佳答案
while a[i] != None:
x, y = pyautogui.center(a[i])
相反,使用
for i in range(len(a)):
x, y = pyautogui.center(a[i])
或者,由于您不使用 i
做任何其他事情,
for item in a:
x, y = pyautogui.center(item)
请在循环中查看您的资料。您应该从那里学到这些技术。
关于python - 索引错误 : list out of range in a while loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58663603/