如何隐藏geckodriver控制台窗口?

时间:2019-09-18 04:07:24

标签: python windows selenium-webdriver console geckodriver

我正在Windows 10上使用python 3.6.7运行Selenium 3.141.0

我的脚本无头运行Firefox驱动程序,但是仍然弹出来自geckodriver的控制台窗口。

from selenium import webdriver

options = webdriver.FirefoxOptions()
options.add_argument('-headless')
driver = webdriver.Firefox(executable_path=r'c:\webdrivers\geckodriver.exe', log_path='C:\webdrivers\geckodriver.log', firefox_options=options)
driver.get('http://10.0.0.102/')

element = WebDriverWait(driver, 20).until(
    EC.presence_of_element_located((By.ID, "body-home-tile-pgDevServ"))
)
button = driver.find_element_by_id('body-home-tile-pgDevServ')
button.click()
element = WebDriverWait(driver, 20).until(
    EC.presence_of_element_located((By.ID, "devserv-printQ-Inp"))
)
button = driver.find_element_by_id('devserv-printQ-Inp')
button.click()

3 个答案:

答案 0 :(得分:3)

我找到了一种方法,基于赵安国的解决方案,在不编辑硒文件本身的情况下解决这个问题,通过猴子补丁到导入的硒模块中:

import functools

from selenium import webdriver

flag = 0x08000000  # No-Window flag
# flag = 0x00000008  # Detached-Process flag, if first doesn't work
webdriver.common.service.subprocess.Popen = functools.partial(
    webdriver.common.service.subprocess.Popen, creationflags=flag)

如果您认为这可能会被多次执行:

import functools
import subprocess

from selenium import webdriver

flag = 0x08000000  # No-Window flag
webdriver.common.service.subprocess.Popen = functools.partial(
    subprocess.Popen, creationflags=flag)

我在 selenium 模块中找不到可以单独使用 creationflags 的地方,所以应该不会破坏任何东西(截至目前)。

自然语言解释:

使用 functools.partial,我们创建了一个“准备好的”Popen 调用,其中已经包含 creationflags 参数。
然后,我们将 selenium 尝试调用的原始 Popen 替换为准备好的 selenium.webdriver.common.service
瞧,每当 Popen 中的某些东西试图创建一个 comm 对象时,它将是已准备好创建标志的对象。

答案 1 :(得分:1)

我入侵了 库,在其中更改了代码, \ AppData \ Roaming \ Python \ Python38 \ site-packages \ selenium \ webdriver \ common \ service.py 第72行及以下,

原始代码 为:

        try:
        cmd = [self.path]
        cmd.extend(self.command_line_args())
        self.process = subprocess.Popen(cmd, env=self.env,
                                        close_fds=platform.system() != 'Windows',
                                        stdout=self.log_file,
                                        stderr=self.log_file,
                                        stdin=PIPE)

再添加两行,就像这样

        try:
        cmd = [self.path]
        cmd.extend(self.command_line_args())
        CREATE_NO_WINDOW = 0x08000000
        self.process = subprocess.Popen(cmd, env=self.env,
                                        close_fds=platform.system() != 'Windows',
                                        stdout=self.log_file,
                                        stderr=self.log_file,
                                        creationflags=CREATE_NO_WINDOW,
                                        stdin=PIPE)

它适用于Windows。

答案 2 :(得分:0)

经过一番混乱之后,似乎添加了options.add_argument('--disable-gpu')有时已将其修复。

从vscode运行脚本,使用Windows Task Scheduler运行脚本。 从powershell或cmd运行不起作用。