【问题标题】:Open file from windows file dialog with python automatically使用python自动从windows文件对话框打开文件
【发布时间】:2016-08-29 21:16:32
【问题描述】:

我进行自动化测试并获得一个文件对话框。我想用 python 或 selenium 从 windows 打开文件对话框中选择一个文件。

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

窗口看起来像:

.

如何做到这一点?

【问题讨论】:

标签: python windows dialog automated-tests ui-automation


【解决方案1】:

考虑使用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()

【讨论】:

【解决方案2】:

您可以使用 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)

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

SendMessage 函数有 4 个参数:窗口处理程序 (hwnd)、要发送的物理密钥 - WM_KEYDOWN (0x0100)、tab (0x09) 的 virtual-key code 和 @ 987654329@ 在第四个参数中。

您还可以发送向上键、向下键、字符、返回等... 使用文档寻求帮助。

我以此为参考:Win32 Python: Getting all window titles

祝你好运!

【讨论】:

  • 你也能描述一下如何点击第一个文件吗?你如何获得元素名称?谢谢!
猜你喜欢
  • 2016-03-14
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多