pyautogui: продолжайте попытки, пока не найдете изображение

Как сделать поиск изображения в определенном месте на экране, в непрерывном поиске с ограничением 'x' секунд, пока изображение не будет найдено? Где, если изображение не найдено, вернуть False. А если изображение найдено, вернуть координаты найденного местоположения... Его также можно автоматически щелкнуть.

Эта функция пришла на ум как триггер для «готово» при ожидании определенного визуального ответа от загружаемой веб-страницы. Я создал автоматизацию для просмотра веб-сайтов в операции, основанной только на визуале, поэтому я не должен использовать библиотеки в качестве запросов или селена. lib pyautogui был лучшим инструментом, который я нашел, но его методы очень примитивны (сосредоточены только на самом необходимом), и я не могу создавать более практичные функции.


person Igor Rogerio    schedule 31.01.2020    source источник


Ответы (1)


О боже... Я уже натерпелся от того, насколько скудны методы pyautogui...

Может быть, это поможет вам.

Ниже есть очень гибкий инструмент для непрерывного и оптимизированного поиска на небольших участках.

Я постарался сделать строку документации как можно более читабельной.

Если функция кажется вам недостаточно понятной, дайте мне знать, что я улучшу строку документации.

import logging
import pyautogui as pag
from PIL import Image
import time

def pag_suf(img, x, y, margin, clicks=0, duration=0, interval=0,
            debug_msg='', time_limit=None, sample_dump=None):
    """
    Pyautogui - Search Until Find
    Searches the image indefinitely at a specific point on the screen
    considering as the search area, the image size plus an expansion margin.
    If found, you can click on the center of the image.
    :param img: String. Fullpath image | List. List of Fullpath image
    :param x: coordinate x
    :param y: coordinate y
    :param margin: Integer. expansion margin to expand the search area
    :param clicks: Integer. number of clicks
    :param duration: Float. duration of mouse movement
    :param interval: Float. sleep time after click
    :param time_limit: Integer. Time limit in seconds
    :param debug_msg: String. Debug message to identify log
    :param sample_dump: String. File name if image .bmp
    :return: List. Coordinates of the center of the found image. |
             False. If time_limit reached.
    """

    is_string = type(img) == str
    list_img = []
    if is_string:
        list_img.append(img)
    else:
        list_img = img

    # Search for image at the indicated location with tolerance margins
    return_value = None
    logging.debug(f"{debug_msg}: Finding...")
    first_loop = True
    start_time = time.time()

    while return_value is None:

        # Scape in time_limit
        if time_limit is not None:
            elapsed_time = time.time() - start_time
            if elapsed_time > time_limit:
                return False
            else:
                pass
        else:
            pass

        if first_loop is False:
            time.sleep(0.5)
        else:
            first_loop = False

        for img in list_img:
            im = Image.open(img)
            # Defining variables
            img_width, img_height = im.size
            coor_x = x - img_width / 2 - margin
            coor_y = y - img_height / 2 - margin
            region_x = img_width + margin * 2
            region_y = img_height + margin * 2

            # Save collected sample
            screen_sample = pag.screenshot(imageFilename=sample_dump,
                                            region=(coor_x, coor_y,
                                                    region_x, region_y))
            return_value = pag.locate(img, screen_sample)
            if return_value is not None:
                # logging.debug(img)
                break

    logging.debug(f"{debug_msg}: Found.")

    click_x = coor_x + return_value[0] + img_width / 2
    click_y = coor_y + return_value[1] + img_height / 2

    # Click on the center of the found location
    if clicks != 0:
        pag.click(click_x, click_y, clicks,
                  duration=duration, interval=interval)

    click_arr = []
    click_arr.append(click_x)
    click_arr.append(click_y)

    return click_arr
person the_RR    schedule 31.01.2020