尝试使用 Pywinauto 将文本发送到应用程序时出错:AttributeError

Error when trying to send text to application with Pywinauto: AttributeError

我正在使用 Pywinauto 自动执行一些与在浏览器登录会话期间打开的应用程序的交互步骤。

让我们调用应用程序 program.exe。它实际上是一个 Chrome 打开并提示输入密码的扩展。

import pywinauto as pwa
from pywinauto import application
from pywinauto import keyboard

app = application.Application()
app = app.Connect(path=r"C:\path\program.exe")                 
win.Part.Click() #not completely sure why i do this
app['Insert password']['Edit'].send('password')

我似乎可以连接到该程序,但是当我尝试向该程序发送文本时出现错误。当我 运行 以上错误发生时:

AttributeError: Neither GUI element (wrapper) nor wrapper method 'send' were found (typo?)

如果我替换这个:

app['Insert password']['Edit'].send('password')

有了这个:

app['Insert password'].SendKeys.send('password')

我收到此错误:

MatchError: Could not find 'SendKeys' in 'dict_keys(['Insert password for MyName:Static', 'Static', 'Insert password for MyName:Edit', 'Edit', 'OK', 'OKButton', 'Button', 'Button0', 'Button1', 'Button2', 'Cancel', 'CancelButton', 'Insert password for MyName:Static0', 'Insert password for MyName:Static1', 'Insert password for MyName:Static2', 'Insert password for MyName:', 'Static0', 'Static1', 'Static2'])'
  • 没有任何控件的方法sendSendKeys 不是方法,而是模块 keyboard 中的一个函数,所以正确的用法是 keyboard.SendKeys('password').

  • 但方法 .type_keys('password') 将控件置于焦点,然后与 keyboard.SendKeys 执行相同的操作。如果密码包含空格,您可能需要使用 with_spaces=True% 等特殊符号必须转义为:{%}。此方法功能强大,因为它支持与 Alt、Shift、Ctrl 等的热键组合。参见 the docs about keyboard module。用于您的案例:

    app['Insert password']['Edit'].type_keys('password', with_spaces=True)


  • 方法 .set_edit_text('password') 可能更有用:它不会逐个字符地键入键,而是将整个原始文本发送到控件(不支持特殊键,仅支持文本)。此方法不需要控件处于焦点。