简体   繁体   中英

Python while/if loop ignoring condition

I'm writing a basic while/if loop to scroll down the page when nextbutton.png is not on the screen, and stop scrolling when the button is on the screen.

It should print True if the button isn't on the screen and print the button's location if it is. Problem is, when I run this code, I get the following output:

True
True
True
True
True
True
True
True
True
True
True
True
True
True
False

The way this code is written, it should never output False , either True or the location. I can provide the website I'm attempting this on with instructions on how to replicate the output, but I suspect that I've made a simple logical mistake in constructing the loop.

import pyautogui
while True:
    if pyautogui.locateOnScreen('nextbutton.png', confidence=0.9) is None:
        print(pyautogui.locateOnScreen('nextbutton.png', confidence=0.9) is None)
        time.sleep(random.randint(0,3000)/1000) 
        pyautogui.press('pagedown')
    else:
        x4, y4 = pyautogui.locateCenterOnScreen('nextbutton.png', confidence=0.9)
        print(x4,y4)
        break

You call the function locateOnScreen() 2 times, and it might return different outputs each time.

I suggest using a variable to hold the output of locateOnScreen() to avoid that race condition. Maybe this can work for you:

import pyautogui

while True:
    v = pyautogui.locateOnScreen('nextbutton.png', confidence=0.9)
    if v is None:
        print(v is None)
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM