pywinauto对接pytest-BDD时登录页鼠标无法定位元素如何解决
pywinauto+pytest-BDD登录页交互异常解决方案
核心优化点
- 移除硬编码坐标与全局鼠标操作,改用pywinauto元素自带的交互方法,自动处理窗口激活、坐标计算逻辑
- 替换固定等待
time.sleep为元素状态等待,避免控件未渲染完成就执行操作 - 修复窗口未激活导致的操作拦截问题,所有元素操作前先确保父窗口处于前台可交互状态
修改后可运行代码
TIMEOUT_SEC = 10 logging.basicConfig(level=logging.DEBUG) mylogger = logging.getLogger() #fixtures @pytest.fixture def get_app_connection(): app_conn = Application(backend='uia').connect(class_name='TFW****Explorer.***Class', timeout=TIMEOUT_SEC) yield app_conn @given(parsers.cfparse('I want to launch the Cegid Application')) def test_launch_application(): os.chdir("path of the application here") Application(backend="uia").start("**.exe") # 等待应用启动完成,CPU占用降到5%以下再进入下一步,替代固定sleep Application(backend='uia').wait_cpu_usage_lower(threshold=5, timeout=TIMEOUT_SEC) return True @when(parsers.cfparse('I enter password')) def test_enterpassword(get_app_connection): dlg = get_app_connection['*** - web authenticationPane'] # 先激活登录窗口,确保操作不会被系统拦截 dlg.set_focus() dlg.wait('ready', timeout=TIMEOUT_SEC) # 定位密码输入框,等待控件可见后直接点击 pwd_input = dlg.child_window(auto_id="pwd", control_type="Edit", timeout=TIMEOUT_SEC) pwd_input.wait('visible', timeout=TIMEOUT_SEC) pwd_input.click_input() # 用type_keys模拟真实输入,触发输入框原生校验逻辑 pwd_input.type_keys("*****", with_spaces=True) @then(parsers.cfparse('I click on login button')) def test_click_loginbtn_function(get_app_connection): dlg = get_app_connection['*** - web authenticationPane'] dlg.wait('ready', timeout=TIMEOUT_SEC) login_btn = dlg.child_window(title="Log in", control_type="Button", timeout=TIMEOUT_SEC) # 等待按钮处于可点击状态后执行点击 login_btn.wait('enabled', timeout=TIMEOUT_SEC) login_btn.click_input()
异常场景补充排查
- 系统DPI缩放不为100%时会导致坐标计算偏移,可在脚本开头添加
pywinauto.win32structures.RECT.set_per_process_dpi_awareness()关闭DPI感知影响 - 若登录面板为WebView2内嵌控件,可在获取dlg后新增
dlg.wait_for_idle()等待控件渲染完成再执行后续操作 - 禁止混用全局
pywinauto.mouse类方法与元素交互方法,全局鼠标操作仅对前台窗口生效,兼容性远低于元素自带的交互方法
内容的提问来源于stack exchange,提问作者mani
相关产品推荐
相关产品推荐

