python - 索引错误 : list out of range in a while loop

标签 python python-3.x pyautogui

因此,当我需要更改代码中以下代码的位置时,我正在编辑我的大型自动化脚本。将代码放在脚本的上部位置后,我突然开始收到以下错误:

  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/

相关文章:

python - 元组实例在枚举类中没有成员(pylint no-member)

python - Beautifulsoup 提取 <li> 和 <ul> 标签并将结果写入 CSV

python - python中的导入是否被认为是动态链接?

Python Panda Dataframe 从列表中计数特定值

python - PyTorch:是否有类似于 Keras 的 fit() 的明确训练循环?

python - 访问另一个模块的 __all__

python - 无法使 python 宏工作,只是执行无限循环

python - pyautogui可以用来防止windows锁屏吗?

python - 无论色调/亮度如何,都使用 PyAutoGUI 在屏幕上定位图像

使用字典理解的 Python 类变量赋值