如何使用pywinauto的Desktop对象连接标题动态变化的微软商店版Spotify
解决微软商店版Spotify窗口标题动态变化的pywinauto自动化问题
针对微软商店版Spotify窗口标题随播放歌曲动态变化、多进程导致的识别问题,可通过以下两种可靠方法解决:
方法一:遍历应用窗口筛选主窗口
利用Application对象的windows()方法遍历所有关联窗口,通过固定类名(微软商店应用主窗口类名通常为Windows.UI.Core.CoreWindow)筛选出主窗口:
import pywinauto import subprocess from pywinauto.application import Application # 启动Spotify subprocess.call("start shell:AppsFolder\SpotifyAB.SpotifyMusic_zpdnekdrzrea0!Spotify", shell=True) # 连接到Spotify应用(UIA后端) app = Application(backend='uia').connect(path="Spotify.exe") # 遍历窗口,筛选主窗口 dlg = None for window in app.windows(): # 结合类名和可见性判断主窗口,可根据实际情况调整属性 if window.class_name() == "Windows.UI.Core.CoreWindow" and window.is_visible(): dlg = window break if not dlg: raise Exception("未找到Spotify主窗口") # 执行自动化操作 dlg.child_window(title="Your Library", control_type="Hyperlink", found_index=0).wait("exists", 30).invoke() dlg.child_window(title="Orchestra", control_type="Hyperlink", found_index=0).wait("exists", 30).invoke() try: dlg.child_window(title="Play Orchestra", control_type="Button").wait("exists", 5).invoke() except: pass # 关闭窗口 dlg.close()
方法二:通过窗口类名+进程关联(需确认主进程)
如果能确定Spotify主窗口所属进程,可直接用Desktop结合类名和进程参数定位:
import pywinauto import subprocess from pywinauto import Desktop from pywinauto.application import Application subprocess.call("start shell:AppsFolder\SpotifyAB.SpotifyMusic_zpdnekdrzrea0!Spotify", shell=True) app = Application(backend='uia').connect(path="Spotify.exe") # 结合类名和进程定位主窗口 dlg = Desktop(backend="uia").window(class_name="Windows.UI.Core.CoreWindow", process=app.process) # 后续操作同方法一 dlg.child_window(title="Your Library", control_type="Hyperlink", found_index=0).wait("exists", 30).invoke() # ... 其他操作
额外提示
- 若不确定窗口类名,可先运行
print([(w.class_name(), w.text()) for w in app.windows()])查看所有窗口的属性,找到固定不变的标识。 - 微软商店应用多进程特性下,遍历窗口的方法兼容性更强,推荐优先使用。
内容的提问来源于stack exchange,提问作者Brian
相关产品推荐
相关产品推荐

