Skip to content

Gerenciadores do Navegador

O módulo de gerenciadores (managers) fornece classes especializadas para gerenciar diferentes aspectos do ciclo de vida e configuração do navegador.

Visão Geral

Os gerenciadores do navegador lidam com responsabilidades específicas na automação do navegador:

pydoll.browser.managers

ChromiumOptionsManager

ChromiumOptionsManager(options=None)

Bases: BrowserOptionsManager

Manages browser options configuration for Chromium-based browsers.

Handles options creation, validation, and applies default CDP arguments for Chrome and Edge browsers.

options instance-attribute

options = options

initialize_options

initialize_options()

Initialize and validate browser options.

Creates ChromiumOptions if none provided, validates existing options, and applies default CDP arguments.

RETURNS DESCRIPTION
ChromiumOptions

Properly configured ChromiumOptions instance.

RAISES DESCRIPTION
InvalidOptionsObject

If provided options is not ChromiumOptions.

add_default_arguments

add_default_arguments()

Add default arguments required for CDP integration.

BrowserProcessManager

BrowserProcessManager(process_creator=None)

Manages browser process lifecycle for CDP automation.

Handles process creation, monitoring, and termination with proper resource cleanup and graceful shutdown.

Initialize browser process manager.

PARAMETER DESCRIPTION
process_creator

Custom function to create browser processes. Must accept command list and return subprocess.Popen object. Uses default subprocess implementation if None.

TYPE: Optional[Callable[[list[str]], Popen]] DEFAULT: None

start_browser_process

start_browser_process(binary_location, port, arguments)

Launch browser process with CDP debugging enabled.

PARAMETER DESCRIPTION
binary_location

Path to browser executable.

TYPE: str

port

TCP port for CDP WebSocket connections.

TYPE: int

arguments

Additional command-line arguments.

TYPE: list[str]

RETURNS DESCRIPTION
Popen

Started browser process instance.

Note

Automatically adds --remote-debugging-port argument.

stop_process

stop_process()

Terminate browser process with graceful shutdown.

Attempts SIGTERM first, then SIGKILL after 15-second timeout. Safe to call even if no process is running.

ProxyManager

ProxyManager(options)

Manages proxy configuration and credentials for CDP automation.

Extracts embedded credentials from proxy URLs, secures authentication information, and sanitizes command-line arguments.

Initialize proxy manager with browser options.

PARAMETER DESCRIPTION
options

Browser options potentially containing proxy configuration. Will be modified if credentials are found.

TYPE: Options

options instance-attribute

options = options

get_proxy_credentials

get_proxy_credentials()

Extract and secure proxy authentication credentials.

Searches for proxy settings, extracts embedded credentials, and sanitizes options to remove credential exposure.

RETURNS DESCRIPTION
tuple[bool, tuple[Optional[str], Optional[str]]]

Tuple of (has_private_proxy, (username, password)).

TempDirectoryManager

TempDirectoryManager(temp_dir_factory=TemporaryDirectory)

Manages temporary directory lifecycle for CDP browser automation.

Creates isolated temporary directories for browser profiles and handles secure cleanup with retry mechanisms for locked files.

Initialize temporary directory manager.

PARAMETER DESCRIPTION
temp_dir_factory

Function to create temporary directories. Must return TemporaryDirectory-compatible object.

TYPE: Callable[[], TemporaryDirectory] DEFAULT: TemporaryDirectory

create_temp_dir

create_temp_dir()

Create and track new temporary directory for browser use.

RETURNS DESCRIPTION
TemporaryDirectory

TemporaryDirectory object for browser --user-data-dir argument.

retry_process_file staticmethod

retry_process_file(func, path, retry_times=10)

Execute file operation with retry logic for locked files.

PARAMETER DESCRIPTION
func

Function to execute on path.

TYPE: Callable[[str], None]

path

File or directory path to operate on.

TYPE: str

retry_times

Maximum retry attempts (negative = unlimited).

TYPE: int DEFAULT: 10

RAISES DESCRIPTION
PermissionError

If operation fails after all retries.

handle_cleanup_error

handle_cleanup_error(func, path, exc_info)

Handle errors during directory cleanup with browser-specific workarounds.

PARAMETER DESCRIPTION
func

Original function that failed.

TYPE: Callable[[str], None]

path

Path that could not be processed.

TYPE: str

exc_info

Exception information tuple.

TYPE: tuple

Note

Handles Chromium-specific locked files like CrashpadMetrics.

cleanup

cleanup()

Remove all tracked temporary directories with error handling.

Uses custom error handler for browser-specific file lock issues. Continues cleanup even if some files resist deletion.

Classes de Gerenciadores

Gerenciador de Processo do Navegador

Gerencia o ciclo de vida do processo do navegador, incluindo iniciar, parar e monitorar os processos do navegador.

pydoll.browser.managers.browser_process_manager

logger module-attribute

logger = getLogger(__name__)

BrowserProcessManager

BrowserProcessManager(process_creator=None)

Manages browser process lifecycle for CDP automation.

Handles process creation, monitoring, and termination with proper resource cleanup and graceful shutdown.

Initialize browser process manager.

PARAMETER DESCRIPTION
process_creator

Custom function to create browser processes. Must accept command list and return subprocess.Popen object. Uses default subprocess implementation if None.

TYPE: Optional[Callable[[list[str]], Popen]] DEFAULT: None

start_browser_process
start_browser_process(binary_location, port, arguments)

Launch browser process with CDP debugging enabled.

PARAMETER DESCRIPTION
binary_location

Path to browser executable.

TYPE: str

port

TCP port for CDP WebSocket connections.

TYPE: int

arguments

Additional command-line arguments.

TYPE: list[str]

RETURNS DESCRIPTION
Popen

Started browser process instance.

Note

Automatically adds --remote-debugging-port argument.

stop_process
stop_process()

Terminate browser process with graceful shutdown.

Attempts SIGTERM first, then SIGKILL after 15-second timeout. Safe to call even if no process is running.

Gerenciador de Opções do Navegador

Lida com as opções de configuração do navegador e argumentos de linha de comando.

pydoll.browser.managers.browser_options_manager

logger module-attribute

logger = getLogger(__name__)

ChromiumOptionsManager

ChromiumOptionsManager(options=None)

Bases: BrowserOptionsManager

Manages browser options configuration for Chromium-based browsers.

Handles options creation, validation, and applies default CDP arguments for Chrome and Edge browsers.

options instance-attribute
options = options
initialize_options
initialize_options()

Initialize and validate browser options.

Creates ChromiumOptions if none provided, validates existing options, and applies default CDP arguments.

RETURNS DESCRIPTION
ChromiumOptions

Properly configured ChromiumOptions instance.

RAISES DESCRIPTION
InvalidOptionsObject

If provided options is not ChromiumOptions.

add_default_arguments
add_default_arguments()

Add default arguments required for CDP integration.

Gerenciador de Proxy

Gerencia a configuração de proxy e autenticação para instâncias do navegador.

pydoll.browser.managers.proxy_manager

logger module-attribute

logger = getLogger(__name__)

ProxyManager

ProxyManager(options)

Manages proxy configuration and credentials for CDP automation.

Extracts embedded credentials from proxy URLs, secures authentication information, and sanitizes command-line arguments.

Initialize proxy manager with browser options.

PARAMETER DESCRIPTION
options

Browser options potentially containing proxy configuration. Will be modified if credentials are found.

TYPE: Options

options instance-attribute
options = options
get_proxy_credentials
get_proxy_credentials()

Extract and secure proxy authentication credentials.

Searches for proxy settings, extracts embedded credentials, and sanitizes options to remove credential exposure.

RETURNS DESCRIPTION
tuple[bool, tuple[Optional[str], Optional[str]]]

Tuple of (has_private_proxy, (username, password)).

Gerenciador de Diretório Temporário

Lida com a criação e limpeza de diretórios temporários usados pelas instâncias do navegador.

pydoll.browser.managers.temp_dir_manager

logger module-attribute

logger = getLogger(__name__)

TempDirectoryManager

TempDirectoryManager(temp_dir_factory=TemporaryDirectory)

Manages temporary directory lifecycle for CDP browser automation.

Creates isolated temporary directories for browser profiles and handles secure cleanup with retry mechanisms for locked files.

Initialize temporary directory manager.

PARAMETER DESCRIPTION
temp_dir_factory

Function to create temporary directories. Must return TemporaryDirectory-compatible object.

TYPE: Callable[[], TemporaryDirectory] DEFAULT: TemporaryDirectory

create_temp_dir
create_temp_dir()

Create and track new temporary directory for browser use.

RETURNS DESCRIPTION
TemporaryDirectory

TemporaryDirectory object for browser --user-data-dir argument.

retry_process_file staticmethod
retry_process_file(func, path, retry_times=10)

Execute file operation with retry logic for locked files.

PARAMETER DESCRIPTION
func

Function to execute on path.

TYPE: Callable[[str], None]

path

File or directory path to operate on.

TYPE: str

retry_times

Maximum retry attempts (negative = unlimited).

TYPE: int DEFAULT: 10

RAISES DESCRIPTION
PermissionError

If operation fails after all retries.

handle_cleanup_error
handle_cleanup_error(func, path, exc_info)

Handle errors during directory cleanup with browser-specific workarounds.

PARAMETER DESCRIPTION
func

Original function that failed.

TYPE: Callable[[str], None]

path

Path that could not be processed.

TYPE: str

exc_info

Exception information tuple.

TYPE: tuple

Note

Handles Chromium-specific locked files like CrashpadMetrics.

cleanup
cleanup()

Remove all tracked temporary directories with error handling.

Uses custom error handler for browser-specific file lock issues. Continues cleanup even if some files resist deletion.

Uso

Os gerenciadores são normalmente usados internamente pelas classes do navegador, como Chrome e Edge. Eles fornecem funcionalidade modular que pode ser composta:

from pydoll.browser.managers.proxy_manager import ProxyManager
from pydoll.browser.managers.temp_dir_manager import TempDirManager

# Gerenciadores são usados internamente pelas classes do navegador
# O uso direto é apenas para cenários avançados
proxy_manager = ProxyManager()
temp_manager = TempDirManager()

Uso Interno

Esses gerenciadores são usados principalmente internamente pelas classes do navegador. O uso direto é recomendado apenas para cenários avançados ou ao estender a biblioteca.