解决 Python 中 OSError: [WinError 193] %1 不是有效的 Win32 应用程序 的问题

这个错误通常是因为尝试运行一个不是有效的应用程序。在你的代码中,你尝试打开一个.lnk文件,但是subprocess.Popen()函数需要传入一个可执行文件的路径。

要解决这个问题,你可以修改代码,将.lnk文件替换为真正的可执行文件的路径。你可以找到.lnk文件的属性,然后查找目标字段,这个字段的值就是真正的可执行文件的路径。

修改后的代码如下:

import subprocess
import pyautogui
import time
import os

# 获取桌面上的小程序的路径
desktop_path = os.path.expanduser("~") + "\Desktop"
program_path = None

for file in os.listdir(desktop_path):
    if file.endswith(".lnk"):
        file_path = os.path.join(desktop_path, file)
        target = subprocess.check_output(['powershell', '-command', '(New-Object -ComObject WScript.Shell).CreateShortcut("{}").TargetPath'.format(file_path)]).decode('utf-8').strip()
        if "国开照片采集工具" in target:
            program_path = target
            break

if program_path:
    # 打开桌面上的小程序
    subprocess.Popen(program_path)

    # 等待小程序打开
    time.sleep(5)

    # 在打开的小程序中找到并点击“我的照片查询”
    my_photos_location = pyautogui.locateOnScreen(r'C:\Users\Administrator\Desktop\我的照片查询.png')
    if my_photos_location:
        my_photos_x, my_photos_y = pyautogui.center(my_photos_location)
        pyautogui.click(my_photos_x, my_photos_y)
    else:
        print("未找到‘我的照片查询’")

    # 等待页面加载
    time.sleep(5)

    # 在打开的页面中找到并点击“考试照片查询”
    exam_photos_location = pyautogui.locateOnScreen(r'C:\Users\Administrator\Desktop\考试照片查询.png')
    if exam_photos_location:
        exam_photos_x, exam_photos_y = pyautogui.center(exam_photos_location)
        pyautogui.click(exam_photos_x, exam_photos_y)
    else:
        print("未找到‘考试照片查询’")
else:
    print("未找到国开照片采集工具")

这段代码会遍历桌面上的所有快捷方式文件(以.lnk结尾),找到目标文件为国开照片采集工具的快捷方式,并获取真正的可执行文件的路径。然后使用获取到的路径打开小程序。

解决 Python 中 OSError: [WinError 193] %1 不是有效的 Win32 应用程序 的问题