首页 > 解决方案 > 网速慢时如何停止pyautogui并恢复之前的程序代码

问题描述

我有一个关于 Pyautogui 的问题。我想点击一个按钮/链接/图片,但在我的国家,互联网速度很慢。所以我试图推迟这个计划。但有时它不起作用。该程序在链接/图像/按钮出现在网站上之前单击它。这就是我无法继续或整个程序失败的原因。

如果按钮/链接/图像正在显示,程序有什么方法可以定位?如果未显示,则应再等待 30 秒或 1 分钟。这就是我希望我的程序每次都能正常工作的方式。我真的很想解决这个问题。我希望你能回复。

标签: pythonpyautogui

解决方案


如果您正在查看一堆具有不同内容的不同网页,这可能会很棘手。但是,如果您知道必须存在的特定图像或链接文本,那么您应该没问题。

下面的 max_wait 是这样程序不会无休止地循环。让它尽可能大。

对于您知道必须显示在页面中的特定图像,您可以尝试

import time
import pyautogui

found_image = False
max_wait = 120

x = time.time()
while (found_image == False) and time.time() - x < max_wait:
    if (pyautogui.locateOnScreen('my_png.png') is not None):
            found_image = True

if found_image: do_main_test()

对于文本,您可以使用 pyautogui 选择所有...

import time
import pyautogui
import pyperclip

x = time.time()
found_text = False
max_wait = 120

while (found_text == False) and time.time() - x < max_wait:
    pyautogui.click(150, 150) # or wherever is in the window
    pyautogui.hotkey('ctrl', 'a')
    pyautogui.hotkey('ctrl', 'c')
    pyautogui.click(x=150, y=150)
    lines = pyperclip.paste()
    found_text = needed_text in lines
    if not found_text: sleep(5) # this is so pyautogui isn't continually highlighting etc.

if found_text: do_main_test()

我不知道跟踪按钮,但我希​​望文本和图像示例有用。当然,您可以指定do_main_test()仅当found_textfound_image为真时才运行。


推荐阅读