python 识别图片在屏幕的位置并点击

def locate_and_click_image(image_path, retry_interval=2, max_retries=5, click_count=1, confidence=None):
    """
    定位图片并点击指定次数,若未找到则重试。

    :param image_path: 图片路径
    :param retry_interval: 重试间隔时间(秒)
    :param max_retries: 最大重试次数
    :param click_count: 点击次数
    :param confidence: 图像匹配的信度(0到1之间),需要安装OpenCV
    :return: 图片的位置 (x, y, width, height) 或 None(如果未找到)
    """
    if not os.path.isfile(image_path):
        print(f"错误:图片路径无效或文件不存在: {image_path}")
        return None

    retries = 0
    while retries < max_retries:
        try:
            if confidence is not None:
                location = pyautogui.locateOnScreen(image_path, confidence=confidence)
            else:
                location = pyautogui.locateOnScreen(image_path)

            if location is not None:
                print(f"找到图片: {image_path}, 位置: {location}")
                center = pyautogui.center(location)
                for _ in range(click_count):
                    pyautogui.click(center)
                    print(f"点击图片中心位置。点击次数: {_ + 1}")
                return location
            else:
                print(f"未找到图片: {image_path}, {retry_interval}秒后重试...(重试次数: {retries + 1}/{max_retries})")
                time.sleep(retry_interval)
                retries += 1
        except pyautogui.ImageNotFoundException:
            print(f"未找到图片: {image_path}, {retry_interval}秒后重试...(重试次数: {retries + 1}/{max_retries})")
            time.sleep(retry_interval)
            retries += 1
    print(f"达到最大重试次数: {max_retries}, 未找到图片: {image_path}")
    return None
f = "H:\\check\\a.png"
if locate_and_click_image(f,confidence=0.9,click_count=2):
    print("11111")
else:
    print("没有啦")

作者:John.liu_Test

物联沃分享整理
物联沃-IOTWORD物联网 » python 识别图片在屏幕的位置并点击

发表回复