导航

Chromedriver 默认情况下,如果有当前控制台,就用当前控制台,没有时,就会自己新建一个, 这样我们如果用 --noconsole 生成执行文件并执行,就会出现弹黑框的问题。

网上有两个常见的解决方案,都需要修改Selenium源码

方案一: creationflags = 134217728

在环境的 Lib\site-packages\selenium\webdriver\common\ 这个目录下打开service.py文件,找到函数start ,在 subprocess.Popen 加上一段代码creationflags=134217728 。

CREATE_NO_WINDOW 这个常量也是这个值,
creationflags=CREATE_NO_WINDOW 是同样的思路。

参看:

方案二 用 subprocess.STARTUPINFO 控制

subprocess.Popen 通过指定一个windows专用的参数
subprocess.STARTUPINFO() 来控制。 然后自己封装一个 NoConsoleChromeWebDriver

不改 Selenium 源码方案

在 Selenium 4.0 以上版本,已经给了解决方案。

但是有个坑:
https://stackoverflow.com/questions/74461847/unable-to-hide-chromedriver-console-with-create-no-window

4.5.0 用

chrome_service.creationflags = CREATE_NO_WINDOW

4.6.0 之后用

chrome_service.creation_flags = CREATE_NO_WINDOW

下面这次提交后,竟然改名了。
https://github.com/SeleniumHQ/selenium/commit/ba04acdf9ea3e53c483cc38a1ae796496e5da9c1

完整的代码示例如下:


    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service as ChromeService
    from subprocess import CREATE_NO_WINDOW
    
    chrome_options = webdriver.ChromeOptions()
    chrome_options.binary_location = r'D:\Test\bin\chrome.exe'
    
    chrome_service = ChromeService(r'D:\Test\bin\chromedriver.exe')
    chrome_service.creation_flags = CREATE_NO_WINDOW
    
    driver = webdriver.Chrome(service=chrome_service, options=chrome_options,executable_path=r'D:\Test\bin\chromedriver.exe')
    driver.get('http://google.com')

参看:
https://stackoverflow.com/questions/33983860/hide-chromedriver-console-in-python

注意,上面的目录要用绝对目录,避免使用的版本冲突,否则很容易出现下面错误:

selenium.common.exceptions.WebDriverException:
Message: unknown error: cannot connect to chrome at 127.0.0.1:62561
from session not created:

This version of ChromeDriver only supports Chrome version 114
Current browser version is 112.0.5615.132

可以用下面函数获得当前执行目录 + 相对目录:

def get_path(relative_path):
    base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)