You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何结合pywinauto与Selenium实现登录?代码报错求助

解决pywinauto连接Selenium打开的Chrome问题

嘿,我来帮你搞定这个问题!你现在的核心困扰是不知道app.connect()里该填什么参数来对接Selenium打开的Chrome,而且代码里还有几个小细节需要调整,我一步步给你拆解:

首先先修正你代码里的小问题:

  • Python的注释是用#,不是//,这个得改过来
  • 你重复初始化了两次app = application.Application(),留一次就够啦

接下来是关键的连接部分,给你两种靠谱的实现方法:

方法一:通过窗口标题匹配(简单直接)

当你用Selenium打开Google后,Chrome窗口的标题里会包含"Google",我们可以用正则匹配标题来定位:

from pywinauto import application
from selenium import webdriver

driver = webdriver.Chrome()
app = application.Application()
driver.get("https://google.co.in")  # 这里把注释改成Python支持的格式啦

# 用正则匹配包含Google的窗口,backend指定uia(Chrome对UIA后端支持更好)
app.connect(title_re=".*Google.*", backend="uia")

方法二:通过进程ID连接(最可靠,避免连错窗口)

如果你的电脑上同时开了多个Chrome窗口,用进程ID就能精准定位到Selenium启动的那个实例:

from pywinauto import application
from selenium import webdriver

driver = webdriver.Chrome()
app = application.Application()
driver.get("https://google.co.in")

# 获取Selenium启动的Chrome进程ID
chrome_pid = driver.service.process.pid
# 通过进程ID精准连接
app.connect(process=chrome_pid, backend="uia")

额外注意事项

  • 一定要指定backend="uia",因为Chrome的现代界面控件用UIA后端比默认的win32后端支持更完善
  • 如果发现还是连不上,试试给Selenium启动Chrome时加个独立用户目录参数,避免和本地已打开的Chrome进程混淆:
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.add_argument("--user-data-dir=C:/temp/chrome_profile")  # 随便指定一个临时目录就行
    driver = webdriver.Chrome(options=options)
    

内容的提问来源于stack exchange,提问作者Shoaib Akhtar

火山引擎 最新活动