python脚本 : 基于opencv和pyautogui的天翼校园掉线自动重连脚本

发布时间 2023-10-21 00:20:47作者: memo2586

无缘无故掉线真的烦(

import cv2
import numpy as np
import pyautogui
import time
from PIL import ImageGrab
import logging

# 读取目标图片
image_message = cv2.imread('message.png')
image_login = cv2.imread('login.png')
h1, w1, _ = image_message.shape
h2, w2, _ = image_login.shape
threshold = 0.8

logging.basicConfig(level=logging.INFO,
                    filename='INFO.log',
                    filemode='a')


def find(image):
    # 获取屏幕截图
    screenshot = ImageGrab.grab()
    screenshot = np.array(screenshot)
    # 在屏幕截图上搜索目标图片
    result = cv2.matchTemplate(screenshot, image, cv2.TM_CCOEFF_NORMED)
    loc = np.where(result >= threshold)
    if len(loc[0]) > 0:
        return [loc[1][0], loc[0][0]]
    else:
        return [0, 0]


while True:
    now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    print(f'[{now}] checking...')
    x, y = find(image_message)

    if x == 0:
        print(f'running normally!')
    else:
        print(f'[{now}] error! Enable automated scripts...')
        logging.info(f'[{now}] error! Enable automated scripts...')
        time.sleep(1)
        print(f'[message_pos]: {x},{y}')
        pyautogui.click(x + w1 // 2, y + h1 // 2)
        time.sleep(1)

        while True:
            x, y = find(image_login)
            if x == 0:
                print("Error! can't not find login! trying again...")
                time.sleep(3)
            else:
                time.sleep(1)
                print(f'[login_pos]: {x},{y}')
                pyautogui.click(x + w2 // 2, y + h2 // 2)
                print("Success! Automation script completed.")

                now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
                logging.info(f'[{now}] Success! Automation script completed.')
                break

    time.sleep(30)

login.png

message.png