用python自动打开windows文件对话框中的文件

kam*_*ame 10 python windows automated-tests dialog ui-automation

我做自动化测试并获得文件对话框.我想从带有python或selenium的windows打开文件对话框中选择一个文件.

注意:该对话框由其他程序提供.我不想用Tkinter创建它.

窗口看起来像:

这个.

这该怎么做?

Rob*_*Rob 6

考虑使用pywinauto包.它具有非常自然的语法来自动化任何GUI程序.

在此输入图像描述

代码示例,在记事本中打开文件.请注意,语法依赖于语言环境(它使用GUI程序中的可见窗口标题/控件标签):

from pywinauto import application
app = application.Application().start_('notepad.exe')
app.Notepad.MenuSelect('File->Open')
# app.[window title].[control name]...
app.Open.Edit.SetText('filename.txt')
app.Open.Open.Click()
Run Code Online (Sandbox Code Playgroud)


Gal*_*man 5

您可以使用ctypes库.

考虑以下代码:

import ctypes

EnumWindows = ctypes.windll.user32.EnumWindows
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
GetWindowText = ctypes.windll.user32.GetWindowTextW
GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
SendMessage = ctypes.windll.user32.SendMessageW
IsWindowVisible = ctypes.windll.user32.IsWindowVisible

def foreach_window(hwnd, lParam):
    if IsWindowVisible(hwnd):
        length = GetWindowTextLength(hwnd)
        buff = ctypes.create_unicode_buffer(length + 1)
        GetWindowText(hwnd, buff, length + 1)

        if(buff.value == "Choose File to Upload"): #This is the window label
            SendMessage(hwnd, 0x0100, 0x09, 0x00000001 )
    return True

EnumWindows(EnumWindowsProc(foreach_window), 0)
Run Code Online (Sandbox Code Playgroud)

你在每个打开的窗口上循环,然后向你选择的那个发送一个击键.

SendMessage函数功能得到4个PARAMS:窗口亨德勒(hwnd)的物理性键发送- WM_KEYDOWN(0100),该虚拟键码tab(0x09)和repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag在第四个参数.

您还可以发送密钥,密钥,字符,返回等...使用文档获取帮助.

我用它作为参考:Win32 Python:获取所有窗口标题

祝好运!