Comandos de Tempo de Execução (Runtime)
Os comandos de tempo de execução fornecem capacidades de execução de JavaScript e gerenciamento do ambiente de tempo de execução.
Visão Geral
O módulo de comandos de tempo de execução habilita a execução de código JavaScript, inspeção de objetos e controle do ambiente de tempo de execução dentro dos contextos do navegador.
pydoll.commands.runtime_commands
RuntimeCommands
A class for interacting with the JavaScript runtime using Chrome DevTools Protocol.
This class provides methods to create commands for evaluating JavaScript expressions, calling functions on JavaScript objects, and retrieving object properties through CDP.
| ATTRIBUTE | DESCRIPTION |
|---|---|
EVALUATE_TEMPLATE |
Template for the Runtime.evaluate command.
TYPE:
|
CALL_FUNCTION_ON_TEMPLATE |
Template for the Runtime.callFunctionOn command.
TYPE:
|
GET_PROPERTIES |
Template for the Runtime.getProperties command.
TYPE:
|
add_binding
staticmethod
Creates a command to add a JavaScript binding.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the binding to add.
TYPE:
|
execution_context_name
|
Name of the execution context to bind to.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
AddBindingCommand
|
Command object to add a JavaScript binding.
TYPE:
|
await_promise
staticmethod
Creates a command to await a JavaScript promise and return its result.
| PARAMETER | DESCRIPTION |
|---|---|
promise_object_id
|
ID of the promise to await.
TYPE:
|
return_by_value
|
Whether to return the result by value instead of reference.
TYPE:
|
generate_preview
|
Whether to generate a preview for the result.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
AwaitPromiseCommand
|
Command object to await a promise.
TYPE:
|
call_function_on
staticmethod
call_function_on(function_declaration, object_id=None, arguments=None, silent=None, return_by_value=None, generate_preview=None, user_gesture=None, await_promise=None, execution_context_id=None, object_group=None, throw_on_side_effect=None, unique_context_id=None, serialization_options=None)
Creates a command to call a function with a given declaration on a specific object.
| PARAMETER | DESCRIPTION |
|---|---|
function_declaration
|
Declaration of the function to call.
TYPE:
|
object_id
|
ID of the object to call the function on.
TYPE:
|
arguments
|
Arguments to pass to the function.
TYPE:
|
silent
|
Whether to silence exceptions.
TYPE:
|
return_by_value
|
Whether to return the result by value instead of reference.
TYPE:
|
generate_preview
|
Whether to generate a preview for the result.
TYPE:
|
user_gesture
|
Whether to treat the call as initiated by user gesture.
TYPE:
|
await_promise
|
Whether to await promise result.
TYPE:
|
execution_context_id
|
ID of the execution context to call the function in.
TYPE:
|
object_group
|
Symbolic group name for the result.
TYPE:
|
throw_on_side_effect
|
Whether to throw if side effect cannot be ruled out.
TYPE:
|
unique_context_id
|
Unique context ID for the function call.
TYPE:
|
serialization_options
|
Serialization options for the result.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
CallFunctionOnCommand
|
Command object to call a function on an object.
TYPE:
|
compile_script
staticmethod
Creates a command to compile a JavaScript expression.
| PARAMETER | DESCRIPTION |
|---|---|
expression
|
JavaScript expression to compile.
TYPE:
|
source_url
|
URL of the source file for the script.
TYPE:
|
persist_script
|
Whether to persist the compiled script.
TYPE:
|
execution_context_id
|
ID of the execution context to compile the script in.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
CompileScriptCommand
|
Command object to compile a script.
TYPE:
|
disable
staticmethod
Disables the runtime domain.
| RETURNS | DESCRIPTION |
|---|---|
DisableCommand
|
Command object to disable the runtime domain.
TYPE:
|
enable
staticmethod
Enables the runtime domain.
| RETURNS | DESCRIPTION |
|---|---|
EnableCommand
|
Command object to enable the runtime domain.
TYPE:
|
evaluate
staticmethod
evaluate(expression, object_group=None, include_command_line_api=None, silent=None, context_id=None, return_by_value=None, generate_preview=None, user_gesture=None, await_promise=None, throw_on_side_effect=None, timeout=None, disable_breaks=None, repl_mode=None, allow_unsafe_eval_blocked_by_csp=None, unique_context_id=None, serialization_options=None)
Creates a command to evaluate a JavaScript expression in the global context.
| PARAMETER | DESCRIPTION |
|---|---|
expression
|
JavaScript expression to evaluate.
TYPE:
|
object_group
|
Symbolic group name for the result.
TYPE:
|
include_command_line_api
|
Whether to include command line API.
TYPE:
|
silent
|
Whether to silence exceptions.
TYPE:
|
context_id
|
ID of the execution context to evaluate in.
TYPE:
|
return_by_value
|
Whether to return the result by value instead of reference.
TYPE:
|
generate_preview
|
Whether to generate a preview for the result.
TYPE:
|
user_gesture
|
Whether to treat evaluation as initiated by user gesture.
TYPE:
|
await_promise
|
Whether to await promise result.
TYPE:
|
throw_on_side_effect
|
Whether to throw if side effect cannot be ruled out.
TYPE:
|
timeout
|
Timeout in milliseconds.
TYPE:
|
disable_breaks
|
Whether to disable breakpoints during evaluation.
TYPE:
|
repl_mode
|
Whether to execute in REPL mode.
TYPE:
|
allow_unsafe_eval_blocked_by_csp
|
Allow unsafe evaluation.
TYPE:
|
unique_context_id
|
Unique context ID for evaluation.
TYPE:
|
serialization_options
|
Serialization for the result.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EvaluateCommand
|
Command object to evaluate JavaScript.
TYPE:
|
get_properties
staticmethod
get_properties(object_id, own_properties=None, accessor_properties_only=None, generate_preview=None, non_indexed_properties_only=None)
Creates a command to get properties of a JavaScript object.
| PARAMETER | DESCRIPTION |
|---|---|
object_id
|
ID of the object to get properties for.
TYPE:
|
own_properties
|
Whether to return only own properties.
TYPE:
|
accessor_properties_only
|
Whether to return only accessor properties.
TYPE:
|
generate_preview
|
Whether to generate previews for property values.
TYPE:
|
non_indexed_properties_only
|
Whether to return only non-indexed properties.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
GetPropertiesCommand
|
Command object to get object properties.
TYPE:
|
global_lexical_scope_names
staticmethod
Creates a command to retrieve names of variables from global lexical scope.
| PARAMETER | DESCRIPTION |
|---|---|
execution_context_id
|
ID of the execution context to get scope names from.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
GlobalLexicalScopeNamesCommand
|
Command object to get global lexical scope names. |
query_objects
staticmethod
Creates a command to query objects with a given prototype.
| PARAMETER | DESCRIPTION |
|---|---|
prototype_object_id
|
ID of the prototype object.
TYPE:
|
object_group
|
Symbolic group name for the results.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
QueryObjectsCommand
|
Command object to query objects.
TYPE:
|
release_object
staticmethod
Creates a command to release a JavaScript object.
| PARAMETER | DESCRIPTION |
|---|---|
object_id
|
ID of the object to release.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ReleaseObjectCommand
|
Command object to release an object.
TYPE:
|
release_object_group
staticmethod
Creates a command to release all objects in a group.
| PARAMETER | DESCRIPTION |
|---|---|
object_group
|
Name of the object group to release.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ReleaseObjectGroupCommand
|
Command object to release an object group. |
remove_binding
staticmethod
Creates a command to remove a JavaScript binding.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the binding to remove.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RemoveBindingCommand
|
Command object to remove a JavaScript binding.
TYPE:
|
run_script
staticmethod
run_script(script_id, execution_context_id=None, object_group=None, silent=None, include_command_line_api=None, return_by_value=None, generate_preview=None, await_promise=None)
Creates a command to run a compiled script.
| PARAMETER | DESCRIPTION |
|---|---|
script_id
|
ID of the compiled script to run.
TYPE:
|
execution_context_id
|
ID of the execution context to run the script in.
TYPE:
|
object_group
|
Symbolic group name for the result.
TYPE:
|
silent
|
Whether to silence exceptions.
TYPE:
|
include_command_line_api
|
Whether to include command line API.
TYPE:
|
return_by_value
|
Whether to return the result by value instead of reference.
TYPE:
|
generate_preview
|
Whether to generate a preview for the result.
TYPE:
|
await_promise
|
Whether to await promise result.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RunScriptCommand
|
Command object to run a script.
TYPE:
|
set_async_call_stack_depth
staticmethod
Creates a command to set the async call stack depth.
| PARAMETER | DESCRIPTION |
|---|---|
max_depth
|
Maximum depth of async call stacks.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SetAsyncCallStackDepthCommand
|
Command object to set async call stack depth. |
set_custom_object_formatter_enabled
staticmethod
Creates a command to enable or disable custom object formatters.
| PARAMETER | DESCRIPTION |
|---|---|
enabled
|
Whether to enable custom object formatters.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SetCustomObjectFormatterEnabledCommand
|
Command object to enable/disable custom object formatters. |
set_max_call_stack_size_to_capture
staticmethod
Creates a command to set the maximum call stack size to capture.
| PARAMETER | DESCRIPTION |
|---|---|
size
|
Maximum call stack size to capture.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SetMaxCallStackSizeToCaptureCommand
|
Command object to set max call stack size. |
Uso
Os comandos de tempo de execução são usados para execução de JavaScript e gerenciamento do tempo de execução:
from pydoll.commands.runtime_commands import evaluate, enable
from pydoll.connection.connection_handler import ConnectionHandler
# Habilitar eventos de tempo de execução
connection = ConnectionHandler()
await enable(connection)
# Executar JavaScript
result = await evaluate(
connection,
expression="document.title",
return_by_value=True
)
print(result.value) # Título da página
Funcionalidades Principais
O módulo de comandos de tempo de execução fornece funções para:
Execução de JavaScript
evaluate()- Executar expressões JavaScriptcall_function_on()- Chamar funções em objetoscompile_script()- Compilar JavaScript para reutilizaçãorun_script()- Executar scripts compilados
Gerenciamento de Objetos
get_properties()- Obter propriedades do objetorelease_object()- Liberar referências de objetorelease_object_group()- Liberar grupos de objetos
Controle de Tempo de Execução
enable()/disable()- Habilitar/desabilitar eventos de tempo de execuçãodiscard_console_entries()- Limpar entradas do consoleset_custom_object_formatter_enabled()- Habilitar formatadores customizados
Manipulação de Exceções
set_async_call_stack_depth()- Definir profundidade da pilha de chamadas assíncronas- Captura e relatório de exceções
- Inspeção de objeto de erro
Uso Avançado
Execução de JavaScript Complexo
# Executar JavaScript complexo com tratamento de erros
script = """
try {
const elements = document.querySelectorAll('.item');
return Array.from(elements).map(el => ({
text: el.textContent,
href: el.href
}));
} catch (error) {
return { error: error.message };
}
"""
result = await evaluate(
connection,
expression=script,
return_by_value=True,
await_promise=True
)
Inspeção de Objeto
# Obter propriedades detalhadas do objeto
properties = await get_properties(
connection,
object_id=object_id,
own_properties=True,
accessor_properties_only=False
)
for prop in properties:
print(f"{prop.name}: {prop.value}")
Integração com Console
Os comandos de tempo de execução se integram ao console do navegador: - Mensagens e erros do console - Chamadas de método da API Console - Formatadores de console customizados
Considerações de Performance
A execução de JavaScript através dos comandos de tempo de execução pode ser mais lenta do que a execução nativa do navegador. Use com moderação para operações complexas.