By default, Chromedriver will use the current console if there is one. If not, it will create a new one by itself, so if we use --noconsole to generate an executable file and execute it, there will be a black box popup problem.
There are two common solutions on the Internet, both of which need to modify the Selenium source code
Option 1: creationflags = 134217728
Open the service.py file in the Lib\site-packages\selenium\webdriver\common\ directory of the environment, find the function start, and add a piece of code creationflags=134217728 to subprocess.Popen.
The constant CREATE_NO_WINDOW also has this value, and
creationflags=CREATE_NO_WINDOW is the same idea.
see:
Scheme 2 is controlled by subprocess.STARTUPINFO
subprocess.Popen is controlled by specifying a windows-specific parameter
subprocess.STARTUPINFO(). Then encapsulate a NoConsoleChromeWebDriver yourself
Do not change the Selenium source code solution
In Selenium 4.0 and above, a solution has been given.
But there is a pit:
python - Unable to hide Chromedriver console with CREATE_NO_WINDOW - Stack Overflow
4.5.0 for
chrome_service.creationflags = CREATE_NO_WINDOW
Use after 4.6.0
chrome_service.creation_flags = CREATE_NO_WINDOW
After the following submission, it was renamed.
https://github.com/SeleniumHQ/selenium/commit/ba04acdf9ea3e53c483cc38a1ae796496e5da9c1
A complete code example is as follows:
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')
参看:
selenium - hide chromeDriver console in python - Stack Overflow
Note that the above directory should use an absolute directory to avoid version conflicts, otherwise the following errors will easily occur:
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
You can use the following function to get the current execution directory + relative directory:
def get_path(relative_path):
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
Make sure the passed path is a fixed path to avoid version conflicts.