siv*_*van 4 python selenium selenium-chromedriver
我在Selenium中使用chrome驱动程序打开chrome,登录路由器,按下一些按钮,上传配置等所有代码都是用Python编写的.
这是获取驱动程序的代码的一部分:
chrome_options = webdriver.ChromeOptions()
prefs = {"download.default_directory": self.user_local}
chrome_options.add_experimental_option("prefs", prefs)
chrome_options.experimental_options.
driver = webdriver.Chrome("chromedriver.exe", chrome_options=chrome_options)
driver.set_window_position(0, 0)
driver.set_window_size(0, 0)
return driver
Run Code Online (Sandbox Code Playgroud)
当我启动我的应用程序时,我得到一个chromedriver.exe控制台(一个黑色的窗口),然后打开一个镀铬窗口,我的所有请求都完成了.
我的问题:在python中有一种隐藏控制台窗口的方法吗?
(正如你所看到的,我也在重新调整chrome窗口的大小,我的偏好是以用户不会注意到屏幕上发生的任何事情的方式做事)
谢谢Sivan
Ali*_*jad 20
我也需要这个,所以我在 GitHub 上实现并提交了这个功能,作为selenium4版本的一部分。我们不再需要为此编辑selenium 库。
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService # Similar thing for firefox also!
from subprocess import CREATE_NO_WINDOW # This flag will only be available in windows
# Define your own service object with the `CREATE_NO_WINDOW ` flag
# If chromedriver.exe is not in PATH, then use:
# ChromeService('/path/to/chromedriver')
chrome_service = ChromeService('chromedriver')
# Use `chrome_service.creationflags` for selenium < 4.6
chrome_service.creation_flags = CREATE_NO_WINDOW
driver = webdriver.Chrome(service=chrome_service)
Run Code Online (Sandbox Code Playgroud)
现在,命令提示符窗口无法打开。当您有一个负责打开 selenium 浏览器的 GUI 桌面应用程序时,这尤其有用。
另请注意,我们只需要在 Windows 中执行此操作。
Cha*_*eer 12
您必须编辑Selenium源代码才能实现此目的.我也是菜鸟,我不完全理解编辑源代码的整体后果,但这是我在Windows 7,Python 2.7上隐藏webdriver控制台窗口所做的工作.
按如下所示找到并编辑此文件:位于Python文件夹中的 Lib\site-packages\selenium\webdriver\common\services.py中.
通过以下方式添加创建标志来编辑Start()函数:creationflags = CREATE_NO_WINDOW
编辑后的方法如下:
def start(self):
"""
Starts the Service.
:Exceptions:
- WebDriverException : Raised either when it can't start the service
or when it can't connect to the service
"""
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, creationflags=CREATE_NO_WINDOW)
except TypeError:
raise
Run Code Online (Sandbox Code Playgroud)
您必须添加相关导入:
from win32process import CREATE_NO_WINDOW
Run Code Online (Sandbox Code Playgroud)
这也适用于Chrome webdriver,因为它们导入相同的文件以启动webdriver进程.
与此相关的问题很多,答案也很多。问题在于,在没有自己的控制台窗口的Python进程中使用Selenium 会导致其chromedriver在新窗口中启动其驱动程序(包括)。
您不必选择直接修改Selenium代码(尽管最终需要这样做),而是要为Chrome WebDriver及其Service使用的类创建自己的子类。该Service班是其中硒实际调用Popen启动服务过程中,如chromedriver.exe(如接受的回答中提到):
import errno
import os
import platform
import subprocess
import sys
import time
import warnings
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common import utils
from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
from selenium.webdriver.chrome import service, webdriver, remote_connection
class HiddenChromeService(service.Service):
def start(self):
try:
cmd = [self.path]
cmd.extend(self.command_line_args())
if platform.system() == 'Windows':
info = subprocess.STARTUPINFO()
info.dwFlags = subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = 0 # SW_HIDE (6 == SW_MINIMIZE)
else:
info = None
self.process = subprocess.Popen(
cmd, env=self.env,
close_fds=platform.system() != 'Windows',
startupinfo=info,
stdout=self.log_file,
stderr=self.log_file,
stdin=subprocess.PIPE)
except TypeError:
raise
except OSError as err:
if err.errno == errno.ENOENT:
raise WebDriverException(
"'%s' executable needs to be in PATH. %s" % (
os.path.basename(self.path), self.start_error_message)
)
elif err.errno == errno.EACCES:
raise WebDriverException(
"'%s' executable may have wrong permissions. %s" % (
os.path.basename(self.path), self.start_error_message)
)
else:
raise
except Exception as e:
raise WebDriverException(
"Executable %s must be in path. %s\n%s" % (
os.path.basename(self.path), self.start_error_message,
str(e)))
count = 0
while True:
self.assert_process_still_running()
if self.is_connectable():
break
count += 1
time.sleep(1)
if count == 30:
raise WebDriverException("Can't connect to the Service %s" % (
self.path,))
class HiddenChromeWebDriver(webdriver.WebDriver):
def __init__(self, executable_path="chromedriver", port=0,
options=None, service_args=None,
desired_capabilities=None, service_log_path=None,
chrome_options=None, keep_alive=True):
if chrome_options:
warnings.warn('use options instead of chrome_options',
DeprecationWarning, stacklevel=2)
options = chrome_options
if options is None:
# desired_capabilities stays as passed in
if desired_capabilities is None:
desired_capabilities = self.create_options().to_capabilities()
else:
if desired_capabilities is None:
desired_capabilities = options.to_capabilities()
else:
desired_capabilities.update(options.to_capabilities())
self.service = HiddenChromeService(
executable_path,
port=port,
service_args=service_args,
log_path=service_log_path)
self.service.start()
try:
RemoteWebDriver.__init__(
self,
command_executor=remote_connection.ChromeRemoteConnection(
remote_server_addr=self.service.service_url,
keep_alive=keep_alive),
desired_capabilities=desired_capabilities)
except Exception:
self.quit()
raise
self._is_remote = False
Run Code Online (Sandbox Code Playgroud)
I removed some of the extra comments and doc string goo for brevity. You would then use this custom WebDriver the same way you'd use the official Chrome one in Selenium:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('headless')
headless_chrome = HiddenChromeWebDriver(chrome_options=options)
headless_chrome.get('http://www.example.com/')
headless_chrome.quit()
Run Code Online (Sandbox Code Playgroud)
Finally, if creating a custom WebDriver is not for you and you don't mind a window flickering and disappearing then you can also use the win32gui library to hide the window after starting up:
# hide chromedriver console on Windows
def enumWindowFunc(hwnd, windowList):
""" win32gui.EnumWindows() callback """
text = win32gui.GetWindowText(hwnd)
className = win32gui.GetClassName(hwnd)
if 'chromedriver' in text.lower() or 'chromedriver' in className.lower():
win32gui.ShowWindow(hwnd, False)
win32gui.EnumWindows(enumWindowFunc, [])
Run Code Online (Sandbox Code Playgroud)
小智 2
启动 Chrome 浏览器时,没有看到带有给定示例代码的 chromedriver 控制台。
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from time import sleep
options = webdriver.ChromeOptions()
prefs = {"download.default_directory": r"C:\New_Download"}
options.add_experimental_option("prefs", prefs)
print(options.experimental_options)
chromeDriverPath = r'C:\drivers\chromedriver.exe'
driver = webdriver.Chrome(chromeDriverPath,chrome_options=options)
driver.get("http://google.com")
driver.set_window_position(0, 0)
driver.set_window_size(0, 0)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9204 次 |
| 最近记录: |