Comandos de Alvo (Target)
Os comandos de alvo (Target) gerenciam os alvos do navegador, incluindo abas, janelas e outros contextos de navegação.
Visão Geral
O módulo de comandos de alvo fornece funcionalidade para criar, gerenciar e controlar os alvos do navegador, como abas, janelas pop-up e service workers.
pydoll.commands.target_commands
TargetCommands
A class for managing browser targets using Chrome DevTools Protocol.
The Target domain of CDP supports additional targets discovery and allows to attach to them. Targets can represent browser tabs, windows, frames, web workers, service workers, etc. The domain provides methods to create, discover, and control these targets.
This class provides methods to create commands for interacting with browser targets, including creating, activating, attaching to, and closing targets through CDP commands.
activate_target
staticmethod
Generates a command to activate (focus) a target.
| PARAMETER | DESCRIPTION |
|---|---|
target_id
|
ID of the target to activate.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Command
|
The CDP command to activate the target.
TYPE:
|
attach_to_target
staticmethod
Generates a command to attach to a target with the given ID.
When attached to a target, you can send commands to it and receive events from it. This is essential for controlling and automating targets like browser tabs.
| PARAMETER | DESCRIPTION |
|---|---|
target_id
|
ID of the target to attach to.
TYPE:
|
flatten
|
If true, enables "flat" access to the session via specifying sessionId attribute in the commands. This is recommended as the non-flattened mode is being deprecated. See https://crbug.com/991325
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Command
|
The CDP command to attach to the target, which will return a sessionId.
TYPE:
|
close_target
staticmethod
Generates a command to close a target.
If the target is a page or a tab, it will be closed. This is equivalent to clicking the close button on a browser tab.
| PARAMETER | DESCRIPTION |
|---|---|
target_id
|
ID of the target to close.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Command
|
The CDP command to close the target, which will return a success flag.
TYPE:
|
create_browser_context
staticmethod
create_browser_context(dispose_on_detach=None, proxy_server=None, proxy_bypass_list=None, origins_with_universal_network_access=None)
Generates a command to create a new empty browser context.
A browser context is similar to an incognito profile but you can have more than one. Each context has its own set of cookies, local storage, and other browser data. This is useful for testing multiple users or isolating sessions.
| PARAMETER | DESCRIPTION |
|---|---|
dispose_on_detach
|
If specified, the context will be disposed when the debugging session disconnects.
TYPE:
|
proxy_server
|
Proxy server string, similar to the one passed to --proxy-server command line argument (e.g., "socks5://192.168.1.100:1080").
TYPE:
|
proxy_bypass_list
|
Proxy bypass list, similar to the one passed to --proxy-bypass-list command line argument (e.g., "*.example.com,localhost").
TYPE:
|
origins_with_universal_network_access
|
An optional list of origins to grant unlimited cross-origin access to. Parts of the URL other than those constituting origin are ignored.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Command
|
The CDP command to create a browser context, which will return the ID of the created context. |
create_target
staticmethod
create_target(url='about:blank', left=None, top=None, width=None, height=None, window_state=None, browser_context_id=None, enable_begin_frame_control=None, new_window=None, background=None, for_tab=None, hidden=None)
Generates a command to create a new page (target).
This is one of the primary methods to open a new tab or window with specific properties such as position, size, and browser context.
| PARAMETER | DESCRIPTION |
|---|---|
url
|
The initial URL the page will navigate to. An empty string indicates about:blank.
TYPE:
|
left
|
Frame left position in device-independent pixels (DIP). Requires newWindow to be true or in headless mode.
TYPE:
|
top
|
Frame top position in DIP. Requires newWindow to be true or in headless mode.
TYPE:
|
width
|
Frame width in DIP.
TYPE:
|
height
|
Frame height in DIP.
TYPE:
|
window_state
|
Frame window state: normal, minimized, maximized, or fullscreen. Default is normal.
TYPE:
|
browser_context_id
|
The browser context to create the page in. If not specified, the default browser context is used.
TYPE:
|
enable_begin_frame_control
|
Whether BeginFrames for this target will be controlled via DevTools (headless shell only, not supported on MacOS yet, false by default).
TYPE:
|
new_window
|
Whether to create a new window or tab (false by default, not supported by headless shell).
TYPE:
|
background
|
Whether to create the target in background or foreground (false by default, not supported by headless shell).
TYPE:
|
for_tab
|
Whether to create the target of type "tab".
TYPE:
|
hidden
|
Whether to create a hidden target. The hidden target is observable via protocol, but not present in the tab UI strip. Cannot be created with forTab:true, newWindow:true or background:false. The life-time of the tab is limited to the life-time of the session.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Command
|
The CDP command to create a target, which will return the ID of the created target.
TYPE:
|
detach_from_target
staticmethod
Generates a command to detach a session from its target.
After detaching, you will no longer receive events from the target and cannot send commands to it.
| PARAMETER | DESCRIPTION |
|---|---|
session_id
|
Session ID to detach. If not specified, detaches all sessions.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Command
|
The CDP command to detach from the target.
TYPE:
|
dispose_browser_context
staticmethod
Generates a command to delete a browser context.
All pages belonging to the browser context will be closed without calling their beforeunload hooks. This is similar to closing an incognito profile.
| PARAMETER | DESCRIPTION |
|---|---|
browser_context_id
|
The ID of the browser context to dispose.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Command
|
The CDP command to dispose the browser context. |
get_browser_contexts
staticmethod
Generates a command to get all browser contexts created with createBrowserContext.
This is useful for obtaining a list of all available contexts for managing multiple isolated browser sessions.
| RETURNS | DESCRIPTION |
|---|---|
Command
|
The CDP command to get all browser contexts, which will return an array of browser context IDs. |
get_targets
staticmethod
Generates a command to retrieve a list of available targets.
Targets include tabs, extensions, web workers, and other attachable entities in the browser. This is useful for discovering what targets exist before attaching to them.
| PARAMETER | DESCRIPTION |
|---|---|
filter
|
Only targets matching the filter will be reported. If filter is not specified and target discovery is currently enabled, a filter used for target discovery is used for consistency.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Command
|
The CDP command to get targets, which will return a list of TargetInfo objects with details about each target.
TYPE:
|
set_auto_attach
staticmethod
Generates a command to control whether to automatically attach to new targets.
This method controls whether to automatically attach to new targets which are considered to be directly related to the current one (for example, iframes or workers). When turned on, it also attaches to all existing related targets. When turned off, it automatically detaches from all currently attached targets.
| PARAMETER | DESCRIPTION |
|---|---|
auto_attach
|
Whether to auto-attach to related targets.
TYPE:
|
wait_for_debugger_on_start
|
Whether to pause new targets when attaching to them. Use Runtime.runIfWaitingForDebugger to run paused targets.
TYPE:
|
flatten
|
Enables "flat" access to the session via specifying sessionId attribute in the commands. This mode is being preferred, and non-flattened mode is being deprecated (see crbug.com/991325).
TYPE:
|
filter
|
Only targets matching filter will be attached.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Command
|
The CDP command to set auto-attach behavior.
TYPE:
|
set_discover_targets
staticmethod
Generates a command to control target discovery.
This method controls whether to discover available targets and notify via targetCreated/targetInfoChanged/targetDestroyed events. Target discovery is useful for monitoring when new tabs, workers, or other targets are created or destroyed.
| PARAMETER | DESCRIPTION |
|---|---|
discover
|
Whether to discover available targets.
TYPE:
|
filter
|
Only targets matching filter will be discovered. If discover is false, filter must be omitted or empty.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Command
|
The CDP command to set target discovery. |
attach_to_browser_target
staticmethod
Generates a command to attach to the browser target.
This is an experimental method that attaches to the browser target, only using flat sessionId mode. The browser target is a special target that represents the browser itself rather than a page or other content.
| PARAMETER | DESCRIPTION |
|---|---|
session_id
|
ID of the session to attach to the browser target.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Command
|
The CDP command to attach to the browser target, which will return a new session ID. |
get_target_info
staticmethod
Generates a command to get information about a specific target.
This experimental method returns detailed information about a target, such as its type, URL, title, and other properties.
| PARAMETER | DESCRIPTION |
|---|---|
target_id
|
ID of the target to get information about.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Command
|
The CDP command to get target information, which will return a TargetInfo object with details about the target.
TYPE:
|
set_remote_locations
staticmethod
Generates a command to enable target discovery for specified remote locations.
This experimental method enables target discovery for remote locations when setDiscoverTargets was set to true. This is useful for discovering targets on remote devices or in different browser instances.
| PARAMETER | DESCRIPTION |
|---|---|
locations
|
list of remote locations, each containing a host and port.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Command
|
The CDP command to set remote locations for target discovery. |
Uso
Os comandos de alvo são usados internamente pelas classes do navegador para gerenciar abas e janelas:
from pydoll.commands.target_commands import get_targets, create_target, close_target
from pydoll.connection.connection_handler import ConnectionHandler
# Obter todos os alvos do navegador
connection = ConnectionHandler()
targets = await get_targets(connection)
# Criar uma nova aba
new_target = await create_target(connection, url="https://example.com")
# Fechar um alvo
await close_target(connection, target_id=new_target.target_id)
Funcionalidades Principais
O módulo de comandos de alvo fornece funções para:
Gerenciamento de Alvo
get_targets()- Listar todos os alvos do navegadorcreate_target()- Criar novas abas ou janelasclose_target()- Fechar alvos específicosactivate_target()- Trazer alvo para o primeiro plano
Informações do Alvo
get_target_info()- Obter informações detalhadas do alvo- Tipos de alvo: page, background_page, service_worker, browser
- Estados do alvo: attached, detached, crashed
Gerenciamento de Sessão
attach_to_target()- Anexar a um alvo para controledetach_from_target()- Desanexar de um alvosend_message_to_target()- Enviar comandos para alvos
Contexto do Navegador
create_browser_context()- Criar contexto de navegador isoladodispose_browser_context()- Remover contexto de navegadorget_browser_contexts()- Listar contextos de navegador
Tipos de Alvos
Diferentes tipos de alvos podem ser gerenciados:
Alvos de Página
# Criar uma nova aba
page_target = await create_target(
connection,
url="https://example.com",
width=1920,
height=1080,
browser_context_id=None # Contexto padrão
)
Janelas Pop-up
# Criar uma janela pop-up
popup_target = await create_target(
connection,
url="https://popup.example.com",
width=800,
height=600,
new_window=True
)
Contextos Anônimos (Incognito)
# Criar contexto de navegador anônimo
incognito_context = await create_browser_context(connection)
# Criar aba no contexto anônimo
incognito_tab = await create_target(
connection,
url="https://private.example.com",
browser_context_id=incognito_context.browser_context_id
)
Headless vs Headed: como os contextos se manifestam
Contextos de navegador são ambientes lógicos isolados. No modo headed (com interface gráfica), a primeira página criada dentro de um novo contexto geralmente abrirá em uma nova janela do SO. No modo headless (sem interface gráfica), nenhuma janela é mostrada — o isolamento permanece puramente lógico (cookies, armazenamento, cache e estado de autenticação ainda são separados por contexto). Prefira contextos em pipelines headless/CI para performance e isolamento limpo.
Recursos Avançados
Eventos de Alvo
Os comandos de alvo funcionam com vários eventos de alvo:
- Target.targetCreated - Novo alvo criado
- Target.targetDestroyed - Alvo fechado
- Target.targetInfoChanged - Informações do alvo atualizadas
- Target.targetCrashed - Alvo falhou (crashed)
Coordenação Multi-Alvo
# Gerenciar múltiplas abas
targets = await get_targets(connection)
page_targets = [t for t in targets if t.type == "page"]
for target in page_targets:
# Realizar operações em cada aba
await activate_target(connection, target_id=target.target_id)
# ... fazer o trabalho nesta aba
Isolamento de Alvo
# Criar contexto de navegador isolado para testes
test_context = await create_browser_context(connection)
# Todos os alvos neste contexto estão isolados
test_tab1 = await create_target(
connection,
url="https://test1.com",
browser_context_id=test_context.browser_context_id
)
test_tab2 = await create_target(
connection,
url="https://test2.com",
browser_context_id=test_context.browser_context_id
)
Integração com o Navegador
Os comandos de alvo são usados principalmente internamente pelas classes de navegador Chrome e Edge. As APIs de navegador de alto nível fornecem métodos mais convenientes para o gerenciamento de abas.