将 webdriver-manager 与 pyinstaller 一起使用时出错

问题描述

我的 webdriver-manager 运行良好,但是当我使用 pyinstaller 制作 .exe 文件时,出现以下错误。我发现,如果我不将 --noconsole 放到 pyinstaller 命令中,它会起作用,但是使用 --noconsole 程序不起作用。 这是我的代码

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://www.google.com/")
driver.quit()

这是我使用 pyinstaller 创建 .exe 文件方法

pyinstaller --onefile --noconsole script.py

这是我得到的错误

Traceback (most recent call last):
  File "script.py",line 797,in program2
  File "webdriver_manager\chrome.py",line 23,in __init__
  File "webdriver_manager\driver.py",line 54,in __init__
  File "webdriver_manager\utils.py",line 139,in chrome_version
  File "os.py",line 983,in popen
  File "subprocess.py",line 804,in __init__
  File "subprocess.py",line 1142,in _get_handles
OSError: [WinError 6] The handle is invalid

感谢您的帮助!

解决方法

如果您使用的是webdriver_manager > 3.4.2的版本,那么这个bug必须已经修复了。

如果您使用的是 webdriver_manager 版本,那么错误仍然存​​在。

Here 是项目 Github 上的拉取请求讨论,它修复了问题。

要自己修复错误,我们需要在 webdriver_manager/utils.py 中进行更改 - 导入附加模块并更改两个函数:

  1. 在开头导入subprocess模块

     import subprocess
    
  2. 请在 def chrome_version() 中找到片段:

     with os.popen(cmd) as stream: 
         stdout = stream.read()
    
  3. 并使用以下内容对其进行更改:

     with subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,stdin=subprocess.DEVNULL,shell=True) as stream:
         stdout = stream.communicate()[0].decode()
    
  4. def firefox_version() 重复上述步骤。

强烈建议仅在您确定可以还原更改的情况下执行上述所有操作。