Saltar a contenido

Clases de fetchers

Aquí puedes consultar los parámetros, atributos y métodos de todas las clases de fetchers.

Puedes importarlas directamente:

from scrapling.fetchers import (
    Fetcher, AsyncFetcher, StealthyFetcher,
    FetcherSession, AsyncStealthySession, StealthySession,
    RemoteSession, AsyncRemoteSession
)

scrapling.fetchers.Fetcher

Fetcher(*args, **kwargs)

Clases base: BaseFetcher


              flowchart TD
              scrapling.fetchers.Fetcher[Fetcher]
              scrapling.engines.toolbelt.custom.BaseFetcher[BaseFetcher]

                              scrapling.engines.toolbelt.custom.BaseFetcher --> scrapling.fetchers.Fetcher
                


              click scrapling.fetchers.Fetcher href "" "scrapling.fetchers.Fetcher"
              click scrapling.engines.toolbelt.custom.BaseFetcher href "" "scrapling.engines.toolbelt.custom.BaseFetcher"
            

Clase Fetcher básica que realiza solicitudes HTTP GET, POST, PUT y DELETE mediante curl_cffi.

Código fuente en scrapling/engines/toolbelt/custom.py
def __init__(self, *args, **kwargs):
    # For backward-compatibility before 0.2.99
    args_str = ", ".join(args) or ""
    kwargs_str = ", ".join(f"{k}={v}" for k, v in kwargs.items()) or ""
    if args_str:
        args_str += ", "

    log.warning(
        f"This logic is deprecated now, and have no effect; It will be removed with v0.3. Use `{self.__class__.__name__}.configure({args_str}{kwargs_str})` instead before fetching"
    )
    pass

__slots__ class-attribute instance-attribute

__slots__ = ()

huge_tree class-attribute instance-attribute

huge_tree = True

adaptive class-attribute instance-attribute

adaptive = False

storage class-attribute instance-attribute

storage = SQLiteStorageSystem

storage_args class-attribute instance-attribute

storage_args = None

keep_comments class-attribute instance-attribute

keep_comments = False

adaptive_domain class-attribute instance-attribute

adaptive_domain = ''

parser_keywords class-attribute instance-attribute

parser_keywords = (
    "huge_tree",
    "adaptive",
    "storage",
    "storage_args",
    "keep_comments",
    "adaptive_domain",
)

display_config classmethod

display_config()
Código fuente en scrapling/engines/toolbelt/custom.py
@classmethod
def display_config(cls):
    return dict(
        huge_tree=cls.huge_tree,
        keep_comments=cls.keep_comments,
        adaptive=cls.adaptive,
        storage=cls.storage,
        storage_args=cls.storage_args,
        adaptive_domain=cls.adaptive_domain,
    )

configure classmethod

configure(**kwargs)

Configura varios argumentos del analizador a la vez de forma global.

PARÁMETRO DESCRIPCIÓN
kwargs

Los argumentos disponibles son huge_tree, keep_comments, adaptive, storage, storage_args y adaptive_domain.

PREDETERMINADO: {}

Código fuente en scrapling/engines/toolbelt/custom.py
@classmethod
def configure(cls, **kwargs):
    """Set multiple arguments for the parser at once globally

    :param kwargs: The keywords can be any arguments of the following: huge_tree, keep_comments, adaptive, storage, storage_args, adaptive_domain
    """
    for key, value in kwargs.items():
        key = key.strip().lower()
        if hasattr(cls, key):
            if key in cls.parser_keywords:
                setattr(cls, key, value)
            else:
                # Yup, no fun allowed LOL
                raise AttributeError(f'Unknown parser argument: "{key}"; maybe you meant {cls.parser_keywords}?')
        else:
            raise ValueError(f'Unknown parser argument: "{key}"; maybe you meant {cls.parser_keywords}?')

    if not kwargs:
        raise AttributeError(f"You must pass a keyword to configure, current keywords: {cls.parser_keywords}?")

get classmethod

get(url, **kwargs)
Código fuente en scrapling/fetchers/requests.py
@classmethod
def get(cls, url: str, **kwargs: Unpack[GetRequestParams]) -> Response:
    return __FetcherClientInstance__.get(url, **_merge_selector_config(cls, kwargs))

post classmethod

post(url, **kwargs)
Código fuente en scrapling/fetchers/requests.py
@classmethod
def post(cls, url: str, **kwargs: Unpack[DataRequestParams]) -> Response:
    return __FetcherClientInstance__.post(url, **_merge_selector_config(cls, kwargs))

put classmethod

put(url, **kwargs)
Código fuente en scrapling/fetchers/requests.py
@classmethod
def put(cls, url: str, **kwargs: Unpack[DataRequestParams]) -> Response:
    return __FetcherClientInstance__.put(url, **_merge_selector_config(cls, kwargs))

delete classmethod

delete(url, **kwargs)
Código fuente en scrapling/fetchers/requests.py
@classmethod
def delete(cls, url: str, **kwargs: Unpack[DataRequestParams]) -> Response:
    return __FetcherClientInstance__.delete(url, **_merge_selector_config(cls, kwargs))

scrapling.fetchers.AsyncFetcher

AsyncFetcher(*args, **kwargs)

Clases base: BaseFetcher


              flowchart TD
              scrapling.fetchers.AsyncFetcher[AsyncFetcher]
              scrapling.engines.toolbelt.custom.BaseFetcher[BaseFetcher]

                              scrapling.engines.toolbelt.custom.BaseFetcher --> scrapling.fetchers.AsyncFetcher
                


              click scrapling.fetchers.AsyncFetcher href "" "scrapling.fetchers.AsyncFetcher"
              click scrapling.engines.toolbelt.custom.BaseFetcher href "" "scrapling.engines.toolbelt.custom.BaseFetcher"
            

Clase Fetcher básica que realiza solicitudes HTTP GET, POST, PUT y DELETE mediante curl_cffi.

Código fuente en scrapling/engines/toolbelt/custom.py
def __init__(self, *args, **kwargs):
    # For backward-compatibility before 0.2.99
    args_str = ", ".join(args) or ""
    kwargs_str = ", ".join(f"{k}={v}" for k, v in kwargs.items()) or ""
    if args_str:
        args_str += ", "

    log.warning(
        f"This logic is deprecated now, and have no effect; It will be removed with v0.3. Use `{self.__class__.__name__}.configure({args_str}{kwargs_str})` instead before fetching"
    )
    pass

__slots__ class-attribute instance-attribute

__slots__ = ()

huge_tree class-attribute instance-attribute

huge_tree = True

adaptive class-attribute instance-attribute

adaptive = False

storage class-attribute instance-attribute

storage = SQLiteStorageSystem

storage_args class-attribute instance-attribute

storage_args = None

keep_comments class-attribute instance-attribute

keep_comments = False

adaptive_domain class-attribute instance-attribute

adaptive_domain = ''

parser_keywords class-attribute instance-attribute

parser_keywords = (
    "huge_tree",
    "adaptive",
    "storage",
    "storage_args",
    "keep_comments",
    "adaptive_domain",
)

display_config classmethod

display_config()
Código fuente en scrapling/engines/toolbelt/custom.py
@classmethod
def display_config(cls):
    return dict(
        huge_tree=cls.huge_tree,
        keep_comments=cls.keep_comments,
        adaptive=cls.adaptive,
        storage=cls.storage,
        storage_args=cls.storage_args,
        adaptive_domain=cls.adaptive_domain,
    )

configure classmethod

configure(**kwargs)

Configura varios argumentos del analizador a la vez de forma global.

PARÁMETRO DESCRIPCIÓN
kwargs

Los argumentos disponibles son huge_tree, keep_comments, adaptive, storage, storage_args y adaptive_domain.

PREDETERMINADO: {}

Código fuente en scrapling/engines/toolbelt/custom.py
@classmethod
def configure(cls, **kwargs):
    """Set multiple arguments for the parser at once globally

    :param kwargs: The keywords can be any arguments of the following: huge_tree, keep_comments, adaptive, storage, storage_args, adaptive_domain
    """
    for key, value in kwargs.items():
        key = key.strip().lower()
        if hasattr(cls, key):
            if key in cls.parser_keywords:
                setattr(cls, key, value)
            else:
                # Yup, no fun allowed LOL
                raise AttributeError(f'Unknown parser argument: "{key}"; maybe you meant {cls.parser_keywords}?')
        else:
            raise ValueError(f'Unknown parser argument: "{key}"; maybe you meant {cls.parser_keywords}?')

    if not kwargs:
        raise AttributeError(f"You must pass a keyword to configure, current keywords: {cls.parser_keywords}?")

get classmethod

get(url, **kwargs)
Código fuente en scrapling/fetchers/requests.py
@classmethod
def get(cls, url: str, **kwargs: Unpack[GetRequestParams]) -> Awaitable[Response]:
    return __AsyncFetcherClientInstance__.get(url, **_merge_selector_config(cls, kwargs))

post classmethod

post(url, **kwargs)
Código fuente en scrapling/fetchers/requests.py
@classmethod
def post(cls, url: str, **kwargs: Unpack[DataRequestParams]) -> Awaitable[Response]:
    return __AsyncFetcherClientInstance__.post(url, **_merge_selector_config(cls, kwargs))

put classmethod

put(url, **kwargs)
Código fuente en scrapling/fetchers/requests.py
@classmethod
def put(cls, url: str, **kwargs: Unpack[DataRequestParams]) -> Awaitable[Response]:
    return __AsyncFetcherClientInstance__.put(url, **_merge_selector_config(cls, kwargs))

delete classmethod

delete(url, **kwargs)
Código fuente en scrapling/fetchers/requests.py
@classmethod
def delete(cls, url: str, **kwargs: Unpack[DataRequestParams]) -> Awaitable[Response]:
    return __AsyncFetcherClientInstance__.delete(url, **_merge_selector_config(cls, kwargs))

scrapling.fetchers.StealthyFetcher

StealthyFetcher(*args, **kwargs)

Clases base: BaseFetcher


              flowchart TD
              scrapling.fetchers.StealthyFetcher[StealthyFetcher]
              scrapling.engines.toolbelt.custom.BaseFetcher[BaseFetcher]

                              scrapling.engines.toolbelt.custom.BaseFetcher --> scrapling.fetchers.StealthyFetcher
                


              click scrapling.fetchers.StealthyFetcher href "" "scrapling.fetchers.StealthyFetcher"
              click scrapling.engines.toolbelt.custom.BaseFetcher href "" "scrapling.engines.toolbelt.custom.BaseFetcher"
            

Clase Fetcher con protección contra detección, basada en Chromium.

Se comporta como un navegador real, supera casi todas las pruebas y protecciones en línea y ofrece muchas opciones de configuración.

Código fuente en scrapling/engines/toolbelt/custom.py
def __init__(self, *args, **kwargs):
    # For backward-compatibility before 0.2.99
    args_str = ", ".join(args) or ""
    kwargs_str = ", ".join(f"{k}={v}" for k, v in kwargs.items()) or ""
    if args_str:
        args_str += ", "

    log.warning(
        f"This logic is deprecated now, and have no effect; It will be removed with v0.3. Use `{self.__class__.__name__}.configure({args_str}{kwargs_str})` instead before fetching"
    )
    pass

__slots__ class-attribute instance-attribute

__slots__ = ()

huge_tree class-attribute instance-attribute

huge_tree = True

adaptive class-attribute instance-attribute

adaptive = False

storage class-attribute instance-attribute

storage = SQLiteStorageSystem

storage_args class-attribute instance-attribute

storage_args = None

keep_comments class-attribute instance-attribute

keep_comments = False

adaptive_domain class-attribute instance-attribute

adaptive_domain = ''

parser_keywords class-attribute instance-attribute

parser_keywords = (
    "huge_tree",
    "adaptive",
    "storage",
    "storage_args",
    "keep_comments",
    "adaptive_domain",
)

display_config classmethod

display_config()
Código fuente en scrapling/engines/toolbelt/custom.py
@classmethod
def display_config(cls):
    return dict(
        huge_tree=cls.huge_tree,
        keep_comments=cls.keep_comments,
        adaptive=cls.adaptive,
        storage=cls.storage,
        storage_args=cls.storage_args,
        adaptive_domain=cls.adaptive_domain,
    )

configure classmethod

configure(**kwargs)

Configura varios argumentos del analizador a la vez de forma global.

PARÁMETRO DESCRIPCIÓN
kwargs

Los argumentos disponibles son huge_tree, keep_comments, adaptive, storage, storage_args y adaptive_domain.

PREDETERMINADO: {}

Código fuente en scrapling/engines/toolbelt/custom.py
@classmethod
def configure(cls, **kwargs):
    """Set multiple arguments for the parser at once globally

    :param kwargs: The keywords can be any arguments of the following: huge_tree, keep_comments, adaptive, storage, storage_args, adaptive_domain
    """
    for key, value in kwargs.items():
        key = key.strip().lower()
        if hasattr(cls, key):
            if key in cls.parser_keywords:
                setattr(cls, key, value)
            else:
                # Yup, no fun allowed LOL
                raise AttributeError(f'Unknown parser argument: "{key}"; maybe you meant {cls.parser_keywords}?')
        else:
            raise ValueError(f'Unknown parser argument: "{key}"; maybe you meant {cls.parser_keywords}?')

    if not kwargs:
        raise AttributeError(f"You must pass a keyword to configure, current keywords: {cls.parser_keywords}?")

fetch classmethod

fetch(url, **kwargs)

Abre un navegador y realiza la solicitud con las opciones que elijas a continuación.

PARÁMETRO DESCRIPCIÓN
url

URL de destino.

TIPO: str

headless

Ejecuta el navegador sin ventana visible, de forma predeterminada, o con una ventana visible.

disable_resources

Descarta solicitudes de recursos innecesarios para mejorar la velocidad. Se descartan los tipos font, image, media, beacon, object, imageset, texttrack, websocket, csp_report y stylesheet.

blocked_domains

Conjunto de dominios cuyas solicitudes se bloquean. También incluye sus subdominios: por ejemplo, "example.com" bloquea "sub.example.com".

block_ads

Bloquea las solicitudes a unos 3500 dominios conocidos de publicidad y seguimiento. Se puede combinar con blocked_domains.

dns_over_https

Envía las consultas DNS por DNS-over-HTTPS de Cloudflare para evitar fugas de DNS al usar proxies.

useragent

Cadena User-Agent que se va a usar. Si no se indica, el fetcher genera una propia de un navegador real del mismo tipo.

cookies

Cookies que se usan en la siguiente solicitud.

network_idle

Espera hasta que la página lleve al menos 500 ms sin conexiones de red.

timeout

Tiempo máximo, en milisegundos, para todas las operaciones y esperas de la página. El valor predeterminado es 30 000.

wait

Tiempo en milisegundos que espera el fetcher cuando todo ha terminado, antes de cerrar la página y devolver el objeto Response.

page_action

Función para automatizar tareas. Recibe el objeto page y se ejecuta después de la navegación.

page_setup

Función que recibe el objeto page y se ejecuta antes de navegar. Úsala para registrar eventos o rutas que deban estar listos antes de cargar la página.

wait_selector

Espera a que un selector CSS concreto esté en el estado indicado.

init_script

Ruta absoluta a un archivo JavaScript que se ejecuta al crear cada página de esta sesión.

locale

Configuración regional del usuario, por ejemplo en-GB o de-DE. Afecta a navigator.language, a la cabecera Accept-Language y al formato de números y fechas. De forma predeterminada, usa la del sistema.

timezone_id

Cambia la zona horaria del navegador. De forma predeterminada, usa la del sistema.

wait_selector_state

Estado que debe alcanzar el selector indicado en wait_selector. El valor predeterminado es attached.

solve_cloudflare

Resuelve los distintos tipos de desafíos Turnstile e Interstitial de Cloudflare antes de devolver la respuesta.

real_chrome

Si tienes Chrome instalado, activa esta opción para que el fetcher abra y use una instancia de ese navegador.

hide_canvas

Añade ruido aleatorio a las operaciones de canvas para evitar que se identifique la huella del navegador.

block_webrtc

Obliga a WebRTC a respetar la configuración del proxy para evitar que se filtre la IP local.

allow_webgl

Está activado de forma predeterminada. Si lo desactivas, se deshabilitan WebGL y WebGL 2.0 por completo. No se recomienda hacerlo porque muchos WAF comprueban si WebGL está activo.

load_dom

Está activado de forma predeterminada. Espera a que todo el JavaScript de las páginas se cargue y se ejecute.

pierce_shadow

Incluye el contenido del Shadow DOM abierto en el HTML de la respuesta. El valor predeterminado es False.

google_search

Está activado de forma predeterminada. Scrapling añade una cabecera referer de Google.

extra_headers

Diccionario de cabeceras adicionales para la solicitud. El referer de google_search tiene prioridad sobre el que definas aquí si usas ambos.

proxy

Proxy que se usa en las solicitudes. Puede ser una cadena o un diccionario solo con las claves 'server', 'username' y 'password'.

user_data_dir

Ruta al directorio de datos del usuario, que guarda las cookies y el almacenamiento local del navegador. De forma predeterminada, se crea un directorio temporal.

extra_flags

Lista de opciones adicionales que se pasan al navegador al iniciarlo.

selector_config

Argumentos que se pasan al crear la clase Selector final.

additional_args

Opciones adicionales para el contexto de Playwright. Tienen prioridad sobre la configuración de Scrapling.

DEVUELVE DESCRIPCIÓN
Response

Objeto Response.

Código fuente en scrapling/fetchers/stealth_chrome.py
@classmethod
def fetch(cls, url: str, **kwargs: Unpack[StealthSession]) -> Response:
    """
    Opens up a browser and do your request based on your chosen options below.

    :param url: Target url.
    :param headless: Run the browser in headless/hidden (default), or headful/visible mode.
    :param disable_resources: Drop requests for unnecessary resources for a speed boost.
        Requests dropped are of type `font`, `image`, `media`, `beacon`, `object`, `imageset`, `texttrack`, `websocket`, `csp_report`, and `stylesheet`.
    :param blocked_domains: A set of domain names to block requests to. Subdomains are also matched (e.g., ``"example.com"`` blocks ``"sub.example.com"`` too).
    :param block_ads: Block requests to ~3,500 known ad/tracking domains. Can be combined with ``blocked_domains``.
    :param dns_over_https: Route DNS queries through Cloudflare's DNS-over-HTTPS to prevent DNS leaks when using proxies.
    :param useragent: Pass a useragent string to be used. Otherwise the fetcher will generate a real Useragent of the same browser and use it.
    :param cookies: Set cookies for the next request.
    :param network_idle: Wait for the page until there are no network connections for at least 500 ms.
    :param timeout: The timeout in milliseconds that is used in all operations and waits through the page. The default is 30,000
    :param wait: The time (milliseconds) the fetcher will wait after everything finishes before closing the page and returning the ` Response ` object.
    :param page_action: Added for automation. A function that takes the `page` object, runs after navigation, and does the automation you need.
    :param page_setup: A function that takes the `page` object, runs before navigation. Use it to register event listeners or routes that must be set up before the page loads.
    :param wait_selector: Wait for a specific CSS selector to be in a specific state.
    :param init_script: An absolute path to a JavaScript file to be executed on page creation for all pages in this session.
    :param locale: Specify user locale, for example, `en-GB`, `de-DE`, etc. Locale will affect navigator.language value, Accept-Language request header value as well as number and date formatting
        rules. Defaults to the system default locale.
    :param timezone_id: Changes the timezone of the browser. Defaults to the system timezone.
    :param wait_selector_state: The state to wait for the selector given with `wait_selector`. The default state is `attached`.
    :param solve_cloudflare: Solves all types of the Cloudflare's Turnstile/Interstitial challenges before returning the response to you.
    :param real_chrome: If you have a Chrome browser installed on your device, enable this, and the Fetcher will launch an instance of your browser and use it.
    :param hide_canvas: Add random noise to canvas operations to prevent fingerprinting.
    :param block_webrtc: Forces WebRTC to respect proxy settings to prevent local IP address leak.
    :param allow_webgl: Enabled by default. Disabling it disables WebGL and WebGL 2.0 support entirely. Disabling WebGL is not recommended as many WAFs now check if WebGL is enabled.
    :param load_dom: Enabled by default, wait for all JavaScript on page(s) to fully load and execute.
    :param pierce_shadow: Include open Shadow DOM content in the response HTML. Defaults to False.
    :param google_search: Enabled by default, Scrapling will set a Google referer header.
    :param extra_headers: A dictionary of extra headers to add to the request. _The referer set by `google_search` takes priority over the referer set here if used together._
    :param proxy: The proxy to be used with requests, it can be a string or a dictionary with the keys 'server', 'username', and 'password' only.
    :param user_data_dir: Path to a User Data Directory, which stores browser session data like cookies and local storage. The default is to create a temporary directory.
    :param extra_flags: A list of additional browser flags to pass to the browser on launch.
    :param selector_config: The arguments that will be passed in the end while creating the final Selector's class.
    :param additional_args: Additional arguments to be passed to Playwright's context as additional settings, and it takes higher priority than Scrapling's settings.
    :return: A `Response` object.
    """
    selector_config = kwargs.get("selector_config", {}) or kwargs.get(
        "custom_config", {}
    )  # Checking `custom_config` for backward compatibility
    if not isinstance(selector_config, dict):
        raise TypeError("Argument `selector_config` must be a dictionary.")

    kwargs["selector_config"] = {**cls._generate_parser_arguments(), **selector_config}

    with StealthySession(**kwargs) as engine:
        return engine.fetch(url)

async_fetch async classmethod

async_fetch(url, **kwargs)

Abre un navegador y realiza la solicitud con las opciones que elijas a continuación.

PARÁMETRO DESCRIPCIÓN
url

URL de destino.

TIPO: str

headless

Ejecuta el navegador sin ventana visible, de forma predeterminada, o con una ventana visible.

disable_resources

Descarta solicitudes de recursos innecesarios para mejorar la velocidad. Se descartan los tipos font, image, media, beacon, object, imageset, texttrack, websocket, csp_report y stylesheet.

blocked_domains

Conjunto de dominios cuyas solicitudes se bloquean. También incluye sus subdominios: por ejemplo, "example.com" bloquea "sub.example.com".

block_ads

Bloquea las solicitudes a unos 3500 dominios conocidos de publicidad y seguimiento. Se puede combinar con blocked_domains.

dns_over_https

Envía las consultas DNS por DNS-over-HTTPS de Cloudflare para evitar fugas de DNS al usar proxies.

useragent

Cadena User-Agent que se va a usar. Si no se indica, el fetcher genera una propia de un navegador real del mismo tipo.

cookies

Cookies que se usan en la siguiente solicitud.

network_idle

Espera hasta que la página lleve al menos 500 ms sin conexiones de red.

timeout

Tiempo máximo, en milisegundos, para todas las operaciones y esperas de la página. El valor predeterminado es 30 000.

wait

Tiempo en milisegundos que espera el fetcher cuando todo ha terminado, antes de cerrar la página y devolver el objeto Response.

page_action

Función para automatizar tareas. Recibe el objeto page y se ejecuta después de la navegación.

page_setup

Función que recibe el objeto page y se ejecuta antes de navegar. Úsala para registrar eventos o rutas que deban estar listos antes de cargar la página.

wait_selector

Espera a que un selector CSS concreto esté en el estado indicado.

init_script

Ruta absoluta a un archivo JavaScript que se ejecuta al crear cada página de esta sesión.

locale

Configuración regional del usuario, por ejemplo en-GB o de-DE. Afecta a navigator.language, a la cabecera Accept-Language y al formato de números y fechas. De forma predeterminada, usa la del sistema.

timezone_id

Cambia la zona horaria del navegador. De forma predeterminada, usa la del sistema.

wait_selector_state

Estado que debe alcanzar el selector indicado en wait_selector. El valor predeterminado es attached.

solve_cloudflare

Resuelve los distintos tipos de desafíos Turnstile e Interstitial de Cloudflare antes de devolver la respuesta.

real_chrome

Si tienes Chrome instalado, activa esta opción para que el fetcher abra y use una instancia de ese navegador.

hide_canvas

Añade ruido aleatorio a las operaciones de canvas para evitar que se identifique la huella del navegador.

block_webrtc

Obliga a WebRTC a respetar la configuración del proxy para evitar que se filtre la IP local.

allow_webgl

Está activado de forma predeterminada. Si lo desactivas, se deshabilitan WebGL y WebGL 2.0 por completo. No se recomienda hacerlo porque muchos WAF comprueban si WebGL está activo.

load_dom

Está activado de forma predeterminada. Espera a que todo el JavaScript de las páginas se cargue y se ejecute.

pierce_shadow

Incluye el contenido del Shadow DOM abierto en el HTML de la respuesta. El valor predeterminado es False.

google_search

Está activado de forma predeterminada. Scrapling añade una cabecera referer de Google.

extra_headers

Diccionario de cabeceras adicionales para la solicitud. El referer de google_search tiene prioridad sobre el que definas aquí si usas ambos.

proxy

Proxy que se usa en las solicitudes. Puede ser una cadena o un diccionario solo con las claves 'server', 'username' y 'password'.

user_data_dir

Ruta al directorio de datos del usuario, que guarda las cookies y el almacenamiento local del navegador. De forma predeterminada, se crea un directorio temporal.

extra_flags

Lista de opciones adicionales que se pasan al navegador al iniciarlo.

selector_config

Argumentos que se pasan al crear la clase Selector final.

additional_args

Opciones adicionales para el contexto de Playwright. Tienen prioridad sobre la configuración de Scrapling.

DEVUELVE DESCRIPCIÓN
Response

Objeto Response.

Código fuente en scrapling/fetchers/stealth_chrome.py
@classmethod
async def async_fetch(cls, url: str, **kwargs: Unpack[StealthSession]) -> Response:
    """
    Opens up a browser and do your request based on your chosen options below.

    :param url: Target url.
    :param headless: Run the browser in headless/hidden (default), or headful/visible mode.
    :param disable_resources: Drop requests for unnecessary resources for a speed boost.
        Requests dropped are of type `font`, `image`, `media`, `beacon`, `object`, `imageset`, `texttrack`, `websocket`, `csp_report`, and `stylesheet`.
    :param blocked_domains: A set of domain names to block requests to. Subdomains are also matched (e.g., ``"example.com"`` blocks ``"sub.example.com"`` too).
    :param block_ads: Block requests to ~3,500 known ad/tracking domains. Can be combined with ``blocked_domains``.
    :param dns_over_https: Route DNS queries through Cloudflare's DNS-over-HTTPS to prevent DNS leaks when using proxies.
    :param useragent: Pass a useragent string to be used. Otherwise the fetcher will generate a real Useragent of the same browser and use it.
    :param cookies: Set cookies for the next request.
    :param network_idle: Wait for the page until there are no network connections for at least 500 ms.
    :param timeout: The timeout in milliseconds that is used in all operations and waits through the page. The default is 30,000
    :param wait: The time (milliseconds) the fetcher will wait after everything finishes before closing the page and returning the ` Response ` object.
    :param page_action: Added for automation. A function that takes the `page` object, runs after navigation, and does the automation you need.
    :param page_setup: A function that takes the `page` object, runs before navigation. Use it to register event listeners or routes that must be set up before the page loads.
    :param wait_selector: Wait for a specific CSS selector to be in a specific state.
    :param init_script: An absolute path to a JavaScript file to be executed on page creation for all pages in this session.
    :param locale: Specify user locale, for example, `en-GB`, `de-DE`, etc. Locale will affect navigator.language value, Accept-Language request header value as well as number and date formatting
        rules. Defaults to the system default locale.
    :param timezone_id: Changes the timezone of the browser. Defaults to the system timezone.
    :param wait_selector_state: The state to wait for the selector given with `wait_selector`. The default state is `attached`.
    :param solve_cloudflare: Solves all types of the Cloudflare's Turnstile/Interstitial challenges before returning the response to you.
    :param real_chrome: If you have a Chrome browser installed on your device, enable this, and the Fetcher will launch an instance of your browser and use it.
    :param hide_canvas: Add random noise to canvas operations to prevent fingerprinting.
    :param block_webrtc: Forces WebRTC to respect proxy settings to prevent local IP address leak.
    :param allow_webgl: Enabled by default. Disabling it disables WebGL and WebGL 2.0 support entirely. Disabling WebGL is not recommended as many WAFs now check if WebGL is enabled.
    :param load_dom: Enabled by default, wait for all JavaScript on page(s) to fully load and execute.
    :param pierce_shadow: Include open Shadow DOM content in the response HTML. Defaults to False.
    :param google_search: Enabled by default, Scrapling will set a Google referer header.
    :param extra_headers: A dictionary of extra headers to add to the request. _The referer set by `google_search` takes priority over the referer set here if used together._
    :param proxy: The proxy to be used with requests, it can be a string or a dictionary with the keys 'server', 'username', and 'password' only.
    :param user_data_dir: Path to a User Data Directory, which stores browser session data like cookies and local storage. The default is to create a temporary directory.
    :param extra_flags: A list of additional browser flags to pass to the browser on launch.
    :param selector_config: The arguments that will be passed in the end while creating the final Selector's class.
    :param additional_args: Additional arguments to be passed to Playwright's context as additional settings, and it takes higher priority than Scrapling's settings.
    :return: A `Response` object.
    """
    selector_config = kwargs.get("selector_config", {}) or kwargs.get(
        "custom_config", {}
    )  # Checking `custom_config` for backward compatibility
    if not isinstance(selector_config, dict):
        raise TypeError("Argument `selector_config` must be a dictionary.")

    kwargs["selector_config"] = {**cls._generate_parser_arguments(), **selector_config}

    async with AsyncStealthySession(**kwargs) as engine:
        return await engine.fetch(url)

Clases de sesión

Sesiones HTTP

scrapling.fetchers.FetcherSession

FetcherSession(
    impersonate="chrome",
    http3=False,
    stealthy_headers=True,
    proxies=None,
    proxy=None,
    proxy_auth=None,
    timeout=30,
    headers=None,
    retries=3,
    retry_delay=1,
    follow_redirects="safe",
    max_redirects=30,
    verify=True,
    cert=None,
    selector_config=None,
    proxy_rotator=None,
)

Gestor de contexto que crea sesiones de Fetcher con la configuración indicada.

Al usar este gestor en un bloque 'with' o 'async with', se obtiene una nueva sesión con los valores predeterminados del gestor. Conviene usar cada instancia para una sola sesión activa a la vez, o para sesiones sucesivas. No se permite volver a entrar en un contexto con la misma instancia si ya tiene una sesión activa.

PARÁMETRO DESCRIPCIÓN
impersonate

Versión del navegador cuya identidad se imita. Puede ser una cadena o una lista de cadenas para elegir una al azar. De forma predeterminada, usa la última versión de Chrome disponible.

TIPO: ImpersonateType PREDETERMINADO: 'chrome'

http3

Indica si se usa HTTP3. El valor predeterminado es False. Puede causar problemas al combinarlo con impersonate.

TIPO: Optional[bool] PREDETERMINADO: False

stealthy_headers

Si está activado, que es el valor predeterminado, crea y añade cabeceras de navegador reales y un referer de Google.

TIPO: Optional[bool] PREDETERMINADO: True

proxies

Diccionario de proxies que se van a usar. Formato: {"http": proxy_url, "https": proxy_url}.

TIPO: Optional[Dict[str, str]] PREDETERMINADO: None

proxy

URL del proxy. Formato: "http://username:password@localhost:8030". No se puede usar junto con proxies.

TIPO: Optional[str] PREDETERMINADO: None

proxy_auth

Autenticación HTTP Basic del proxy como tupla (username, password).

TIPO: Optional[Tuple[str, str]] PREDETERMINADO: None

timeout

Segundos de espera antes de agotar el tiempo máximo.

TIPO: Optional[int | float] PREDETERMINADO: 30

headers

Cabeceras que se incluyen en cada solicitud de la sesión.

TIPO: Optional[Dict[str, str]] PREDETERMINADO: None

retries

Número de reintentos. El valor predeterminado es 3.

TIPO: Optional[int] PREDETERMINADO: 3

retry_delay

Segundos de espera entre reintentos. El valor predeterminado es 1 segundo.

TIPO: Optional[int] PREDETERMINADO: 1

follow_redirects

Indica si se siguen redirecciones. El valor predeterminado es "safe": sigue las redirecciones, pero rechaza las que apuntan a IP internas o privadas como protección contra SSRF. Usa True para seguirlas todas sin restricciones.

TIPO: FollowRedirects PREDETERMINADO: 'safe'

max_redirects

Número máximo de redirecciones. El valor predeterminado es 30. Usa -1 para no limitarlo.

TIPO: int PREDETERMINADO: 30

verify

Indica si se verifican los certificados HTTPS. El valor predeterminado es True.

TIPO: bool PREDETERMINADO: True

cert

Tupla (cert, key) con los nombres de los archivos del certificado del cliente y su clave.

TIPO: Optional[str | Tuple[str, str]] PREDETERMINADO: None

selector_config

Argumentos que se pasan al crear la clase Selector final.

TIPO: Optional[Dict] PREDETERMINADO: None

proxy_rotator

Instancia de ProxyRotator para rotar los proxies de forma automática.

TIPO: Optional[ProxyRotator] PREDETERMINADO: None

Código fuente en scrapling/engines/static.py
def __init__(
    self,
    impersonate: ImpersonateType = "chrome",
    http3: Optional[bool] = False,
    stealthy_headers: Optional[bool] = True,
    proxies: Optional[Dict[str, str]] = None,
    proxy: Optional[str] = None,
    proxy_auth: Optional[Tuple[str, str]] = None,
    timeout: Optional[int | float] = 30,
    headers: Optional[Dict[str, str]] = None,
    retries: Optional[int] = 3,
    retry_delay: Optional[int] = 1,
    follow_redirects: FollowRedirects = "safe",
    max_redirects: int = 30,
    verify: bool = True,
    cert: Optional[str | Tuple[str, str]] = None,
    selector_config: Optional[Dict] = None,
    proxy_rotator: Optional[ProxyRotator] = None,
):
    """
    :param impersonate: Browser version to impersonate. Can be a single browser string or a list of browser strings for random selection. (Default: latest available Chrome version)
    :param http3: Whether to use HTTP3. Defaults to False. It might be problematic if used it with `impersonate`.
    :param stealthy_headers: If enabled (default), it creates and adds real browser headers. It also sets a Google referer header.
    :param proxies: Dict of proxies to use. Format: {"http": proxy_url, "https": proxy_url}.
    :param proxy: Proxy URL to use. Format: "http://username:password@localhost:8030".
                 Cannot be used together with the `proxies` parameter.
    :param proxy_auth: HTTP basic auth for proxy, tuple of (username, password).
    :param timeout: Number of seconds to wait before timing out.
    :param headers: Headers to include in the session with every request.
    :param retries: Number of retry attempts. Defaults to 3.
    :param retry_delay: Number of seconds to wait between retry attempts. Defaults to 1 second.
    :param follow_redirects: Whether to follow redirects. Defaults to "safe", which follows redirects but rejects those targeting internal/private IPs (SSRF protection). Pass True to follow all redirects without restriction.
    :param max_redirects: Maximum number of redirects. Default 30, use -1 for unlimited.
    :param verify: Whether to verify HTTPS certificates. Defaults to True.
    :param cert: Tuple of (cert, key) filenames for the client certificate.
    :param selector_config: Arguments passed when creating the final Selector class.
    :param proxy_rotator: A ProxyRotator instance for automatic proxy rotation.
    """
    self._default_impersonate: ImpersonateType = impersonate
    self._stealth = stealthy_headers
    self._default_proxies = proxies or {}
    self._default_proxy = proxy or None
    self._default_proxy_auth = proxy_auth or None
    self._default_timeout = timeout
    self._default_headers = headers or {}
    self._default_retries = retries
    self._default_retry_delay = retry_delay
    self._default_follow_redirects = follow_redirects
    self._default_max_redirects = max_redirects
    self._default_verify = verify
    self._default_cert = cert
    self._default_http3 = http3
    self.selector_config = selector_config or {}
    self._is_alive = False
    self._client: _SyncSessionLogic | _ASyncSessionLogic | None = None
    self._proxy_rotator = proxy_rotator

__slots__ class-attribute instance-attribute

__slots__ = (
    "_default_impersonate",
    "_stealth",
    "_default_proxies",
    "_default_proxy",
    "_default_proxy_auth",
    "_default_timeout",
    "_default_headers",
    "_default_retries",
    "_default_retry_delay",
    "_default_follow_redirects",
    "_default_max_redirects",
    "_default_verify",
    "_default_cert",
    "_default_http3",
    "selector_config",
    "_client",
    "_is_alive",
    "_proxy_rotator",
)

selector_config instance-attribute

selector_config = selector_config or {}

__enter__

__enter__()

Crea y devuelve una nueva sesión síncrona de Fetcher.

Código fuente en scrapling/engines/static.py
def __enter__(self) -> _SyncSessionLogic:
    """Creates and returns a new synchronous Fetcher Session"""
    if self._client is None:
        # Use **vars(self) to avoid repeating all parameters
        config = {k.replace("_default_", ""): getattr(self, k) for k in self.__slots__ if k.startswith("_default")}
        config["stealthy_headers"] = self._stealth
        config["selector_config"] = self.selector_config
        config["proxy_rotator"] = self._proxy_rotator
        self._client = _SyncSessionLogic(**config)
        try:
            result = self._client.__enter__()
        except Exception:
            self._client = None
            raise
        self._is_alive = True
        return result
    raise RuntimeError("This FetcherSession instance already has an active synchronous session.")

__exit__

__exit__(exc_type, exc_val, exc_tb)
Código fuente en scrapling/engines/static.py
def __exit__(self, exc_type, exc_val, exc_tb):
    if self._client is not None and isinstance(self._client, _SyncSessionLogic):
        self._client.__exit__(exc_type, exc_val, exc_tb)
        self._client = None
        self._is_alive = False
        return
    raise RuntimeError("Cannot exit invalid session")

__aenter__ async

__aenter__()

Crea y devuelve una nueva sesión asíncrona.

Código fuente en scrapling/engines/static.py
async def __aenter__(self) -> _ASyncSessionLogic:
    """Creates and returns a new asynchronous Session."""
    if self._client is None:
        # Use **vars(self) to avoid repeating all parameters
        config = {k.replace("_default_", ""): getattr(self, k) for k in self.__slots__ if k.startswith("_default")}
        config["stealthy_headers"] = self._stealth
        config["selector_config"] = self.selector_config
        config["proxy_rotator"] = self._proxy_rotator
        self._client = _ASyncSessionLogic(**config)
        try:
            result = await self._client.__aenter__()
        except Exception:
            self._client = None
            raise
        self._is_alive = True
        return result
    raise RuntimeError("This FetcherSession instance already has an active asynchronous session.")

__aexit__ async

__aexit__(exc_type, exc_val, exc_tb)
Código fuente en scrapling/engines/static.py
async def __aexit__(self, exc_type, exc_val, exc_tb):
    if self._client is not None and isinstance(self._client, _ASyncSessionLogic):
        await self._client.__aexit__(exc_type, exc_val, exc_tb)
        self._client = None
        self._is_alive = False
        return
    raise RuntimeError("Cannot exit invalid session")

Sesiones sigilosas

scrapling.fetchers.StealthySession

StealthySession(**kwargs)

Clases base: SyncSession, StealthySessionMixin


              flowchart TD
              scrapling.fetchers.StealthySession[StealthySession]
              scrapling.engines._browsers._base.SyncSession[SyncSession]
              scrapling.engines._browsers._base.StealthySessionMixin[StealthySessionMixin]
              scrapling.engines._browsers._base.BaseSessionMixin[BaseSessionMixin]

                              scrapling.engines._browsers._base.SyncSession --> scrapling.fetchers.StealthySession
                
                scrapling.engines._browsers._base.StealthySessionMixin --> scrapling.fetchers.StealthySession
                                scrapling.engines._browsers._base.BaseSessionMixin --> scrapling.engines._browsers._base.StealthySessionMixin
                



              click scrapling.fetchers.StealthySession href "" "scrapling.fetchers.StealthySession"
              click scrapling.engines._browsers._base.SyncSession href "" "scrapling.engines._browsers._base.SyncSession"
              click scrapling.engines._browsers._base.StealthySessionMixin href "" "scrapling.engines._browsers._base.StealthySessionMixin"
              click scrapling.engines._browsers._base.BaseSessionMixin href "" "scrapling.engines._browsers._base.BaseSessionMixin"
            

Gestor de sesiones de navegador con protección contra detección y un grupo de páginas reutilizables.

Gestor de sesiones de navegador con un grupo de páginas reutilizables. De forma predeterminada, usa un contexto persistente y un directorio temporal para el perfil de usuario.

PARÁMETRO DESCRIPCIÓN
record_requests

Guarda las solicitudes y respuestas del navegador que han terminado. Omite las fallidas y las pendientes. El valor predeterminado es False.

max_recorded_requests

Número máximo de solicitudes guardadas por sesión. El valor predeterminado es 1000. Se eliminan las entradas más antiguas.

headless

Ejecuta el navegador sin ventana visible, de forma predeterminada, o con una ventana visible.

disable_resources

Descarta solicitudes de recursos innecesarios para mejorar la velocidad. Se descartan los tipos font, image, media, beacon, object, imageset, texttrack, websocket, csp_report y stylesheet.

blocked_domains

Conjunto de dominios cuyas solicitudes se bloquean. También incluye sus subdominios: por ejemplo, "example.com" bloquea "sub.example.com".

useragent

Cadena User-Agent que se va a usar. Si no se indica, el fetcher genera una propia de un navegador real del mismo tipo.

cookies

Cookies que se usan en la siguiente solicitud.

network_idle

Espera hasta que la página lleve al menos 500 ms sin conexiones de red.

timeout

Tiempo máximo, en milisegundos, para todas las operaciones y esperas de la página. El valor predeterminado es 30 000.

wait

Tiempo en milisegundos que espera el fetcher cuando todo ha terminado, antes de cerrar la página y devolver el objeto Response.

page_action

Función para automatizar tareas. Recibe el objeto page y se ejecuta después de la navegación.

page_setup

Función que recibe el objeto page y se ejecuta antes de navegar. Úsala para registrar eventos o rutas que deban estar listos antes de cargar la página.

wait_selector

Espera a que un selector CSS concreto esté en el estado indicado.

init_script

Ruta absoluta a un archivo JavaScript que se ejecuta al crear cada página de esta sesión.

locale

Configuración regional del usuario, por ejemplo en-GB o de-DE. Afecta a navigator.language, a la cabecera Accept-Language y al formato de números y fechas. De forma predeterminada, usa la del sistema.

timezone_id

Cambia la zona horaria del navegador. De forma predeterminada, usa la del sistema.

wait_selector_state

Estado que debe alcanzar el selector indicado en wait_selector. El valor predeterminado es attached.

solve_cloudflare

Resuelve los distintos tipos de desafíos Turnstile e Interstitial de Cloudflare antes de devolver la respuesta.

real_chrome

Si tienes Chrome instalado, activa esta opción para que el fetcher abra y use una instancia de ese navegador.

hide_canvas

Añade ruido aleatorio a las operaciones de canvas para evitar que se identifique la huella del navegador.

block_webrtc

Obliga a WebRTC a respetar la configuración del proxy para evitar que se filtre la IP local.

allow_webgl

Está activado de forma predeterminada. Si lo desactivas, se deshabilitan WebGL y WebGL 2.0 por completo. No se recomienda hacerlo porque muchos WAF comprueban si WebGL está activo.

load_dom

Está activado de forma predeterminada. Espera a que todo el JavaScript de las páginas se cargue y se ejecute.

pierce_shadow

Incluye el contenido del Shadow DOM abierto en el HTML de la respuesta. El valor predeterminado es False.

google_search

Está activado de forma predeterminada. Scrapling añade una cabecera referer de Google.

extra_headers

Diccionario de cabeceras adicionales para la solicitud. El referer de google_search tiene prioridad sobre el que definas aquí si usas ambos.

proxy

Proxy que se usa en las solicitudes. Puede ser una cadena o un diccionario solo con las claves 'server', 'username' y 'password'.

user_data_dir

Ruta al directorio de datos del usuario, que guarda las cookies y el almacenamiento local del navegador. De forma predeterminada, se crea un directorio temporal.

extra_flags

Lista de opciones adicionales que se pasan al navegador al iniciarlo.

selector_config

Argumentos que se pasan al crear la clase Selector final.

additional_args

Opciones adicionales para el contexto de Playwright. Tienen prioridad sobre la configuración de Scrapling.

Código fuente en scrapling/engines/_browsers/_stealth.py
def __init__(self, **kwargs: Unpack[StealthSession]):
    """A Browser session manager with page pooling, it's using a persistent browser Context by default with a temporary user profile directory.

    :param record_requests: Save completed browser requests and responses. Failed or unfinished requests are omitted. Defaults to False.
    :param max_recorded_requests: Maximum retained requests per session. Defaults to 1000; older entries are removed.
    :param headless: Run the browser in headless/hidden (default), or headful/visible mode.
    :param disable_resources: Drop requests for unnecessary resources for a speed boost.
        Requests dropped are of type `font`, `image`, `media`, `beacon`, `object`, `imageset`, `texttrack`, `websocket`, `csp_report`, and `stylesheet`.
    :param blocked_domains: A set of domain names to block requests to. Subdomains are also matched (e.g., ``"example.com"`` blocks ``"sub.example.com"`` too).
    :param useragent: Pass a useragent string to be used. Otherwise the fetcher will generate a real Useragent of the same browser and use it.
    :param cookies: Set cookies for the next request.
    :param network_idle: Wait for the page until there are no network connections for at least 500 ms.
    :param timeout: The timeout in milliseconds that is used in all operations and waits through the page. The default is 30,000
    :param wait: The time (milliseconds) the fetcher will wait after everything finishes before closing the page and returning the ` Response ` object.
    :param page_action: Added for automation. A function that takes the `page` object, runs after navigation, and does the automation you need.
    :param page_setup: A function that takes the `page` object, runs before navigation. Use it to register event listeners or routes that must be set up before the page loads.
    :param wait_selector: Wait for a specific CSS selector to be in a specific state.
    :param init_script: An absolute path to a JavaScript file to be executed on page creation for all pages in this session.
    :param locale: Specify user locale, for example, `en-GB`, `de-DE`, etc. Locale will affect navigator.language value, Accept-Language request header value as well as number and date formatting
        rules. Defaults to the system default locale.
    :param timezone_id: Changes the timezone of the browser. Defaults to the system timezone.
    :param wait_selector_state: The state to wait for the selector given with `wait_selector`. The default state is `attached`.
    :param solve_cloudflare: Solves all types of the Cloudflare's Turnstile/Interstitial challenges before returning the response to you.
    :param real_chrome: If you have a Chrome browser installed on your device, enable this, and the Fetcher will launch an instance of your browser and use it.
    :param hide_canvas: Add random noise to canvas operations to prevent fingerprinting.
    :param block_webrtc: Forces WebRTC to respect proxy settings to prevent local IP address leak.
    :param allow_webgl: Enabled by default. Disabling it disables WebGL and WebGL 2.0 support entirely. Disabling WebGL is not recommended as many WAFs now check if WebGL is enabled.
    :param load_dom: Enabled by default, wait for all JavaScript on page(s) to fully load and execute.
    :param pierce_shadow: Include open Shadow DOM content in the response HTML. Defaults to False.
    :param google_search: Enabled by default, Scrapling will set a Google referer header.
    :param extra_headers: A dictionary of extra headers to add to the request. _The referer set by `google_search` takes priority over the referer set here if used together._
    :param proxy: The proxy to be used with requests, it can be a string or a dictionary with the keys 'server', 'username', and 'password' only.
    :param user_data_dir: Path to a User Data Directory, which stores browser session data like cookies and local storage. The default is to create a temporary directory.
    :param extra_flags: A list of additional browser flags to pass to the browser on launch.
    :param selector_config: The arguments that will be passed in the end while creating the final Selector's class.
    :param additional_args: Additional arguments to be passed to Playwright's context as additional settings, and it takes higher priority than Scrapling's settings.
    """
    self.__validate__(**kwargs)
    super().__init__(
        record_requests=self._config.record_requests,
        max_recorded_requests=self._config.max_recorded_requests,
    )

max_pages instance-attribute

max_pages = max_pages

network instance-attribute

network = NetworkRecorder(
    enabled=record_requests,
    max_requests=max_recorded_requests,
)

page_pool instance-attribute

page_pool = PagePool(max_pages)

playwright instance-attribute

playwright = None

context instance-attribute

context = None

browser instance-attribute

browser = None

__slots__ class-attribute instance-attribute

__slots__ = (
    "_config",
    "_context_options",
    "_browser_options",
    "_user_data_dir",
    "_headers_keys",
    "max_pages",
    "page_pool",
    "_max_wait_for_page",
    "playwright",
    "context",
)

__validate_routine__

__validate_routine__(params, model)
Código fuente en scrapling/engines/_browsers/_base.py
def __validate_routine__(
    self, params: Dict, model: type[PlaywrightConfig] | type[StealthConfig]
) -> PlaywrightConfig | StealthConfig:
    # Dark color scheme bypasses the 'prefersLightColor' check in creepjs
    self._context_options: Dict[str, Any] = {"color_scheme": "dark", "device_scale_factor": 2}
    self._browser_options: Dict[str, Any] = {
        "args": DEFAULT_ARGS,
        "ignore_default_args": HARMFUL_ARGS,
    }
    if "__max_pages" in params:
        params["max_pages"] = params.pop("__max_pages")

    config = validate(params, model=model)
    self._headers_keys = (
        {header.lower() for header in config.extra_headers.keys()} if config.extra_headers else set()
    )

    return config

__generate_context_options__

__generate_context_options__()
Código fuente en scrapling/engines/_browsers/_base.py
def __generate_context_options__(self) -> None:
    config: PlaywrightConfig | StealthConfig = self._config
    self._context_options.update(
        {
            "proxy": config.proxy,
            "timezone_id": config.timezone_id,
            "extra_http_headers": config.extra_headers,
        }
    )
    # The default useragent in the headful is always correct now in the current versions of Playwright
    if config.useragent:
        self._context_options["user_agent"] = config.useragent
    elif not config.useragent and config.headless:
        self._context_options["user_agent"] = (
            __default_chrome_useragent__ if config.real_chrome else __default_useragent__
        )

    if config.additional_args:
        self._context_options.update(config.additional_args)

__generate_options__

__generate_options__(extra_flags=None)
Código fuente en scrapling/engines/_browsers/_base.py
def __generate_options__(self, extra_flags: Tuple | None = None) -> None:
    self.__generate_context_options__()
    config = self._config
    flags = self._browser_options["args"]
    if config.extra_flags or extra_flags:
        flags = list(set(tuple(flags) + tuple(extra_flags or ()) + tuple(config.extra_flags or ())))
    if config.dns_over_https:
        flags = list(flags) + ["--dns-over-https-templates=https://cloudflare-dns.com/dns-query"]
    if config.locale:
        base_lang = config.locale.split("-")[0].lower()
        accept_lang = f"{config.locale},{base_lang}" if base_lang != config.locale.lower() else config.locale
        flags = list(flags) + [f"--lang={config.locale}", f"--accept-lang={accept_lang}"]
    self._browser_options.update(
        {"args": flags, "headless": config.headless, "channel": "chrome" if config.real_chrome else "chromium"}
    )
    if config.executable_path:
        self._browser_options["executable_path"] = config.executable_path
    self._user_data_dir = config.user_data_dir

__validate__

__validate__(**params)
Código fuente en scrapling/engines/_browsers/_base.py
def __validate__(self, **params):
    self._config = self.__validate_routine__(params, model=self._config_class)
    self._context_options.update(
        {
            "is_mobile": False,
            "has_touch": False,
            # I'm thinking about disabling it to rest from all Service Workers' headache, but let's keep it as it is for now
            "service_workers": "allow",
            "ignore_https_errors": True,
            "screen": {"width": 1920, "height": 1080},
            "viewport": {"width": 1920, "height": 1080},
            "permissions": ["geolocation", "notifications"],
        }
    )
    self.__generate_stealth_options()

save_state

save_state(path)

Guarda las cookies, el almacenamiento local e IndexedDB en un archivo JSON compatible con Playwright.

Requiere una sesión iniciada sin rotación de proxies. No guarda sessionStorage.

Código fuente en scrapling/engines/_browsers/_base.py
def save_state(self, path: str | Path) -> None:
    """Save cookies, local storage and IndexedDB to a Playwright-compatible JSON file.

    Requires a started session without proxy rotation. Does not save sessionStorage.
    """
    if not self._is_alive or self.context is None:
        raise RuntimeError("Session state requires a started browser session without proxy rotation")
    self.context.storage_state(path=Path(path), indexed_db=True)

load_state

load_state(path)

Sustituye las cookies, el almacenamiento local e IndexedDB por los datos de un archivo JSON compatible con Playwright.

Requiere una sesión iniciada sin rotación de proxies. Carga o recarga las páginas para usar el inicio de sesión restaurado.

Código fuente en scrapling/engines/_browsers/_base.py
def load_state(self, path: str | Path) -> None:
    """Replace cookies, local storage and IndexedDB from a Playwright-compatible JSON file.

    Requires a started session without proxy rotation. Fetch or reload pages to use the restored login.
    """
    if not self._is_alive or self.context is None:
        raise RuntimeError("Session state requires a started browser session without proxy rotation")
    self.context.set_storage_state(path)

close_pages

close_pages()

Cierra todas las pestañas del grupo de la sesión. La siguiente solicitud abre una pestaña nueva.

Código fuente en scrapling/engines/_browsers/_base.py
def close_pages(self) -> None:
    """Close every open tab in the session's pool. The next request opens a fresh tab."""
    for page_info in self.page_pool.clear():
        with suppress(Exception):
            page_info.page.close()

close

close()

Cierra todos los recursos.

Código fuente en scrapling/engines/_browsers/_base.py
def close(self):  # pragma: no cover
    """Close all resources"""
    self.network._detach()
    if not self._is_alive:
        return

    self.close_pages()
    try:
        if self.context and self._owns_context:
            self.context.close()
    finally:
        self.context = None
        try:
            if self.browser:
                self.browser.close()
        finally:
            self.browser = None
            try:
                if self.playwright:
                    self.playwright.stop()
            finally:
                self.playwright = None
                self._is_alive = False

__enter__

__enter__()
Código fuente en scrapling/engines/_browsers/_base.py
def __enter__(self):
    self.start()
    return self

__exit__

__exit__(exc_type, exc_val, exc_tb)
Código fuente en scrapling/engines/_browsers/_base.py
def __exit__(self, exc_type, exc_val, exc_tb):
    self.close()

get_pool_stats

get_pool_stats()

Obtiene estadísticas del grupo de páginas actual.

Código fuente en scrapling/engines/_browsers/_base.py
def get_pool_stats(self) -> Dict[str, int]:
    """Get statistics about the current page pool"""
    return {
        "total_pages": self.page_pool.pages_count,
        "busy_pages": self.page_pool.busy_count,
        "max_pages": self.max_pages,
    }

start

start()

Crea un navegador para esta instancia y su contexto.

Código fuente en scrapling/engines/_browsers/_stealth.py
def start(self) -> None:
    """Create a browser for this instance and context."""
    if not self.playwright:
        self.playwright = sync_playwright().start()
        self._is_alive = True
        try:
            self._create_context()
            if self.context:
                self.context = self._initialize_context(self._config, self.context)
        except BaseException:
            with suppress(Exception):
                self.close()
            raise
    else:
        raise RuntimeError("Session has been already started")

fetch

fetch(url, **kwargs)

Abre el navegador y realiza la solicitud con las opciones elegidas.

PARÁMETRO DESCRIPCIÓN
url

URL de destino.

TIPO: str

google_search

Está activado de forma predeterminada. Scrapling añade una cabecera referer de Google.

timeout

Tiempo máximo, en milisegundos, para todas las operaciones y esperas de la página. El valor predeterminado es 30 000.

wait

Tiempo en milisegundos que espera el fetcher cuando todo ha terminado, antes de cerrar la página y devolver el objeto Response.

page_action

Función para automatizar tareas. Recibe el objeto page y se ejecuta después de la navegación.

page_setup

Función que recibe el objeto page y se ejecuta antes de navegar. Úsala para registrar eventos o rutas que deban estar listos antes de cargar la página.

extra_headers

Diccionario de cabeceras adicionales para la solicitud. El referer de google_search tiene prioridad sobre el que definas aquí si usas ambos.

disable_resources

Descarta solicitudes de recursos innecesarios para mejorar la velocidad. Se descartan los tipos font, image, media, beacon, object, imageset, texttrack, websocket, csp_report y stylesheet.

blocked_domains

Conjunto de dominios cuyas solicitudes se bloquean. También incluye sus subdominios: por ejemplo, "example.com" bloquea "sub.example.com".

wait_selector

Espera a que un selector CSS concreto esté en el estado indicado.

wait_selector_state

Estado que debe alcanzar el selector indicado en wait_selector. El valor predeterminado es attached.

network_idle

Espera hasta que la página lleve al menos 500 ms sin conexiones de red.

load_dom

Está activado de forma predeterminada. Espera a que todo el JavaScript de las páginas se cargue y se ejecute.

pierce_shadow

Incluye el contenido del Shadow DOM abierto en el HTML de la respuesta. El valor predeterminado es False.

solve_cloudflare

Resuelve los distintos tipos de desafíos Turnstile e Interstitial de Cloudflare antes de devolver la respuesta.

selector_config

Argumentos que se pasan al crear la clase Selector final.

proxy

Proxy fijo que sustituye al rotador y al proxy de la sesión. Se crea un nuevo contexto de navegador para usarlo.

DEVUELVE DESCRIPCIÓN
Response

Objeto Response.

Código fuente en scrapling/engines/_browsers/_stealth.py
def fetch(self, url: str, **kwargs: Unpack[StealthFetchParams]) -> Response:
    """Opens up the browser and do your request based on your chosen options.

    :param url: The Target url.
    :param google_search: Enabled by default, Scrapling will set a Google referer header.
    :param timeout: The timeout in milliseconds that is used in all operations and waits through the page. The default is 30,000
    :param wait: The time (milliseconds) the fetcher will wait after everything finishes before closing the page and returning the ` Response ` object.
    :param page_action: Added for automation. A function that takes the `page` object, runs after navigation, and does the automation you need.
    :param page_setup: A function that takes the `page` object, runs before navigation. Use it to register event listeners or routes that must be set up before the page loads.
    :param extra_headers: A dictionary of extra headers to add to the request. _The referer set by `google_search` takes priority over the referer set here if used together._
    :param disable_resources: Drop requests for unnecessary resources for a speed boost.
        Requests dropped are of type `font`, `image`, `media`, `beacon`, `object`, `imageset`, `texttrack`, `websocket`, `csp_report`, and `stylesheet`.
    :param blocked_domains: A set of domain names to block requests to. Subdomains are also matched (e.g., ``"example.com"`` blocks ``"sub.example.com"`` too).
    :param wait_selector: Wait for a specific CSS selector to be in a specific state.
    :param wait_selector_state: The state to wait for the selector given with `wait_selector`. The default state is `attached`.
    :param network_idle: Wait for the page until there are no network connections for at least 500 ms.
    :param load_dom: Enabled by default, wait for all JavaScript on page(s) to fully load and execute.
    :param pierce_shadow: Include open Shadow DOM content in the response HTML. Defaults to False.
    :param solve_cloudflare: Solves all types of the Cloudflare's Turnstile/Interstitial challenges before returning the response to you.
    :param selector_config: The arguments that will be passed in the end while creating the final Selector's class.
    :param proxy: Static proxy to override rotator and session proxy. A new browser context will be created and used with it.
    :return: A `Response` object.
    """
    static_proxy = kwargs.pop("proxy", None)
    if not self._owns_context:
        static_proxy = None

    params = _validate(kwargs, self, StealthConfig)
    if not self._is_alive:  # pragma: no cover
        raise RuntimeError("Context manager has been closed")

    request_headers_keys = {h.lower() for h in params.extra_headers.keys()} if params.extra_headers else set()
    referer = (
        "https://www.google.com/" if (params.google_search and "referer" not in request_headers_keys) else None
    )

    for attempt in range(self._config.retries):
        proxy: Optional[ProxyType] = None
        if self._config.proxy_rotator and static_proxy is None:
            proxy = self._config.proxy_rotator.get_proxy()
        else:
            proxy = static_proxy

        with self._page_generator(
            params.timeout, params.extra_headers, params.disable_resources, proxy, params.blocked_domains
        ) as page_info:
            final_response: List = [None]
            page = page_info.page
            handler = self._create_response_handler(page_info, final_response)
            page.on("response", handler)
            try:
                if params.page_setup:
                    try:
                        params.page_setup(page)
                    except Exception as e:  # pragma: no cover
                        log.error(f"Error executing page_setup: {e}")

                try:
                    first_response = page.goto(url, referer=referer)
                    self._wait_for_page_stability(page, params.load_dom, params.network_idle)

                    if not first_response:
                        raise RuntimeError(f"Failed to get response for {url}")

                    if params.solve_cloudflare:
                        self._cloudflare_solver(page)
                        # Make sure the page is fully loaded after the captcha
                        self._wait_for_page_stability(page, params.load_dom, params.network_idle)

                    if params.page_action:
                        try:
                            _ = params.page_action(page)
                        except Exception as e:  # pragma: no cover
                            log.error(f"Error executing page_action: {e}")

                    if params.wait_selector:
                        try:
                            waiter: Locator = page.locator(params.wait_selector)
                            waiter.first.wait_for(state=params.wait_selector_state)
                            self._wait_for_page_stability(page, params.load_dom, params.network_idle)
                        except Exception as e:  # pragma: no cover
                            log.error(f"Error waiting for selector {params.wait_selector}: {e}")

                    page.wait_for_timeout(params.wait)

                    response = ResponseFactory.from_playwright_response(
                        page,
                        first_response,
                        final_response[0],
                        params.selector_config,
                        meta={"proxy": proxy},
                        pierce_shadow=params.pierce_shadow,
                    )
                    return response

                except Exception as e:
                    page_info.mark_error()
                    if attempt < self._config.retries - 1:
                        if is_proxy_error(e):
                            log.warning(
                                f"Proxy '{proxy}' failed (attempt {attempt + 1}) | Retrying in {self._config.retry_delay}s..."
                            )
                        else:
                            log.warning(
                                f"Attempt {attempt + 1} failed: {e}. Retrying in {self._config.retry_delay}s..."
                            )
                        time_sleep(self._config.retry_delay)
                    else:
                        log.error(f"Failed after {self._config.retries} attempts: {e}")
                        raise
            finally:
                page.remove_listener("response", handler)

    raise RuntimeError("Request failed")  # pragma: no cover

scrapling.fetchers.AsyncStealthySession

AsyncStealthySession(**kwargs)

Clases base: AsyncSession, StealthySessionMixin


              flowchart TD
              scrapling.fetchers.AsyncStealthySession[AsyncStealthySession]
              scrapling.engines._browsers._base.AsyncSession[AsyncSession]
              scrapling.engines._browsers._base.StealthySessionMixin[StealthySessionMixin]
              scrapling.engines._browsers._base.BaseSessionMixin[BaseSessionMixin]

                              scrapling.engines._browsers._base.AsyncSession --> scrapling.fetchers.AsyncStealthySession
                
                scrapling.engines._browsers._base.StealthySessionMixin --> scrapling.fetchers.AsyncStealthySession
                                scrapling.engines._browsers._base.BaseSessionMixin --> scrapling.engines._browsers._base.StealthySessionMixin
                



              click scrapling.fetchers.AsyncStealthySession href "" "scrapling.fetchers.AsyncStealthySession"
              click scrapling.engines._browsers._base.AsyncSession href "" "scrapling.engines._browsers._base.AsyncSession"
              click scrapling.engines._browsers._base.StealthySessionMixin href "" "scrapling.engines._browsers._base.StealthySessionMixin"
              click scrapling.engines._browsers._base.BaseSessionMixin href "" "scrapling.engines._browsers._base.BaseSessionMixin"
            

Gestor asíncrono de sesiones de navegador con protección contra detección y un grupo de páginas reutilizables.

Gestor de sesiones de navegador con un grupo de páginas reutilizables. De forma predeterminada, usa un contexto persistente y un directorio temporal para el perfil de usuario.

PARÁMETRO DESCRIPCIÓN
record_requests

Guarda las solicitudes y respuestas del navegador que han terminado. Omite las fallidas y las pendientes. El valor predeterminado es False.

max_recorded_requests

Número máximo de solicitudes guardadas por sesión. El valor predeterminado es 1000. Se eliminan las entradas más antiguas.

headless

Ejecuta el navegador sin ventana visible, de forma predeterminada, o con una ventana visible.

disable_resources

Descarta solicitudes de recursos innecesarios para mejorar la velocidad. Se descartan los tipos font, image, media, beacon, object, imageset, texttrack, websocket, csp_report y stylesheet.

blocked_domains

Conjunto de dominios cuyas solicitudes se bloquean. También incluye sus subdominios: por ejemplo, "example.com" bloquea "sub.example.com".

useragent

Cadena User-Agent que se va a usar. Si no se indica, el fetcher genera una propia de un navegador real del mismo tipo.

cookies

Cookies que se usan en la siguiente solicitud.

network_idle

Espera hasta que la página lleve al menos 500 ms sin conexiones de red.

timeout

Tiempo máximo, en milisegundos, para todas las operaciones y esperas de la página. El valor predeterminado es 30 000.

wait

Tiempo en milisegundos que espera el fetcher cuando todo ha terminado, antes de cerrar la página y devolver el objeto Response.

page_action

Función para automatizar tareas. Recibe el objeto page y se ejecuta después de la navegación.

page_setup

Función que recibe el objeto page y se ejecuta antes de navegar. Úsala para registrar eventos o rutas que deban estar listos antes de cargar la página.

wait_selector

Espera a que un selector CSS concreto esté en el estado indicado.

init_script

Ruta absoluta a un archivo JavaScript que se ejecuta al crear cada página de esta sesión.

locale

Configuración regional del usuario, por ejemplo en-GB o de-DE. Afecta a navigator.language, a la cabecera Accept-Language y al formato de números y fechas. De forma predeterminada, usa la del sistema.

timezone_id

Cambia la zona horaria del navegador. De forma predeterminada, usa la del sistema.

wait_selector_state

Estado que debe alcanzar el selector indicado en wait_selector. El valor predeterminado es attached.

solve_cloudflare

Resuelve los distintos tipos de desafíos Turnstile e Interstitial de Cloudflare antes de devolver la respuesta.

real_chrome

Si tienes Chrome instalado, activa esta opción para que el fetcher abra y use una instancia de ese navegador.

hide_canvas

Añade ruido aleatorio a las operaciones de canvas para evitar que se identifique la huella del navegador.

block_webrtc

Obliga a WebRTC a respetar la configuración del proxy para evitar que se filtre la IP local.

allow_webgl

Está activado de forma predeterminada. Si lo desactivas, se deshabilitan WebGL y WebGL 2.0 por completo. No se recomienda hacerlo porque muchos WAF comprueban si WebGL está activo.

load_dom

Está activado de forma predeterminada. Espera a que todo el JavaScript de las páginas se cargue y se ejecute.

pierce_shadow

Incluye el contenido del Shadow DOM abierto en el HTML de la respuesta. El valor predeterminado es False.

google_search

Está activado de forma predeterminada. Scrapling añade una cabecera referer de Google.

extra_headers

Diccionario de cabeceras adicionales para la solicitud. El referer de google_search tiene prioridad sobre el que definas aquí si usas ambos.

proxy

Proxy que se usa en las solicitudes. Puede ser una cadena o un diccionario solo con las claves 'server', 'username' y 'password'.

user_data_dir

Ruta al directorio de datos del usuario, que guarda las cookies y el almacenamiento local del navegador. De forma predeterminada, se crea un directorio temporal.

extra_flags

Lista de opciones adicionales que se pasan al navegador al iniciarlo.

selector_config

Argumentos que se pasan al crear la clase Selector final.

additional_args

Opciones adicionales para el contexto de Playwright. Tienen prioridad sobre la configuración de Scrapling.

Código fuente en scrapling/engines/_browsers/_stealth.py
def __init__(self, **kwargs: Unpack[StealthSession]):
    """A Browser session manager with page pooling, it's using a persistent browser Context by default with a temporary user profile directory.

    :param record_requests: Save completed browser requests and responses. Failed or unfinished requests are omitted. Defaults to False.
    :param max_recorded_requests: Maximum retained requests per session. Defaults to 1000; older entries are removed.
    :param headless: Run the browser in headless/hidden (default), or headful/visible mode.
    :param disable_resources: Drop requests for unnecessary resources for a speed boost.
        Requests dropped are of type `font`, `image`, `media`, `beacon`, `object`, `imageset`, `texttrack`, `websocket`, `csp_report`, and `stylesheet`.
    :param blocked_domains: A set of domain names to block requests to. Subdomains are also matched (e.g., ``"example.com"`` blocks ``"sub.example.com"`` too).
    :param useragent: Pass a useragent string to be used. Otherwise the fetcher will generate a real Useragent of the same browser and use it.
    :param cookies: Set cookies for the next request.
    :param network_idle: Wait for the page until there are no network connections for at least 500 ms.
    :param timeout: The timeout in milliseconds that is used in all operations and waits through the page. The default is 30,000
    :param wait: The time (milliseconds) the fetcher will wait after everything finishes before closing the page and returning the ` Response ` object.
    :param page_action: Added for automation. A function that takes the `page` object, runs after navigation, and does the automation you need.
    :param page_setup: A function that takes the `page` object, runs before navigation. Use it to register event listeners or routes that must be set up before the page loads.
    :param wait_selector: Wait for a specific CSS selector to be in a specific state.
    :param init_script: An absolute path to a JavaScript file to be executed on page creation for all pages in this session.
    :param locale: Specify user locale, for example, `en-GB`, `de-DE`, etc. Locale will affect navigator.language value, Accept-Language request header value as well as number and date formatting
        rules. Defaults to the system default locale.
    :param timezone_id: Changes the timezone of the browser. Defaults to the system timezone.
    :param wait_selector_state: The state to wait for the selector given with `wait_selector`. The default state is `attached`.
    :param solve_cloudflare: Solves all types of the Cloudflare's Turnstile/Interstitial challenges before returning the response to you.
    :param real_chrome: If you have a Chrome browser installed on your device, enable this, and the Fetcher will launch an instance of your browser and use it.
    :param hide_canvas: Add random noise to canvas operations to prevent fingerprinting.
    :param block_webrtc: Forces WebRTC to respect proxy settings to prevent local IP address leak.
    :param allow_webgl: Enabled by default. Disabling it disables WebGL and WebGL 2.0 support entirely. Disabling WebGL is not recommended as many WAFs now check if WebGL is enabled.
    :param load_dom: Enabled by default, wait for all JavaScript on page(s) to fully load and execute.
    :param pierce_shadow: Include open Shadow DOM content in the response HTML. Defaults to False.
    :param google_search: Enabled by default, Scrapling will set a Google referer header.
    :param extra_headers: A dictionary of extra headers to add to the request. _The referer set by `google_search` takes priority over the referer set here if used together._
    :param proxy: The proxy to be used with requests, it can be a string or a dictionary with the keys 'server', 'username', and 'password' only.
    :param user_data_dir: Path to a User Data Directory, which stores browser session data like cookies and local storage. The default is to create a temporary directory.
    :param extra_flags: A list of additional browser flags to pass to the browser on launch.
    :param selector_config: The arguments that will be passed in the end while creating the final Selector's class.
    :param additional_args: Additional arguments to be passed to Playwright's context as additional settings, and it takes higher priority than Scrapling's settings.
    """
    self.__validate__(**kwargs)
    super().__init__(
        max_pages=self._config.max_pages,
        record_requests=self._config.record_requests,
        max_recorded_requests=self._config.max_recorded_requests,
    )

max_pages instance-attribute

max_pages = max_pages

network instance-attribute

network = NetworkRecorder(
    enabled=record_requests,
    max_requests=max_recorded_requests,
    asynchronous=True,
)

page_pool instance-attribute

page_pool = PagePool(max_pages)

playwright instance-attribute

playwright = None

context instance-attribute

context = None

browser instance-attribute

browser = None

__slots__ class-attribute instance-attribute

__slots__ = (
    "_config",
    "_context_options",
    "_browser_options",
    "_user_data_dir",
    "_headers_keys",
)

__validate_routine__

__validate_routine__(params, model)
Código fuente en scrapling/engines/_browsers/_base.py
def __validate_routine__(
    self, params: Dict, model: type[PlaywrightConfig] | type[StealthConfig]
) -> PlaywrightConfig | StealthConfig:
    # Dark color scheme bypasses the 'prefersLightColor' check in creepjs
    self._context_options: Dict[str, Any] = {"color_scheme": "dark", "device_scale_factor": 2}
    self._browser_options: Dict[str, Any] = {
        "args": DEFAULT_ARGS,
        "ignore_default_args": HARMFUL_ARGS,
    }
    if "__max_pages" in params:
        params["max_pages"] = params.pop("__max_pages")

    config = validate(params, model=model)
    self._headers_keys = (
        {header.lower() for header in config.extra_headers.keys()} if config.extra_headers else set()
    )

    return config

__generate_context_options__

__generate_context_options__()
Código fuente en scrapling/engines/_browsers/_base.py
def __generate_context_options__(self) -> None:
    config: PlaywrightConfig | StealthConfig = self._config
    self._context_options.update(
        {
            "proxy": config.proxy,
            "timezone_id": config.timezone_id,
            "extra_http_headers": config.extra_headers,
        }
    )
    # The default useragent in the headful is always correct now in the current versions of Playwright
    if config.useragent:
        self._context_options["user_agent"] = config.useragent
    elif not config.useragent and config.headless:
        self._context_options["user_agent"] = (
            __default_chrome_useragent__ if config.real_chrome else __default_useragent__
        )

    if config.additional_args:
        self._context_options.update(config.additional_args)

__generate_options__

__generate_options__(extra_flags=None)
Código fuente en scrapling/engines/_browsers/_base.py
def __generate_options__(self, extra_flags: Tuple | None = None) -> None:
    self.__generate_context_options__()
    config = self._config
    flags = self._browser_options["args"]
    if config.extra_flags or extra_flags:
        flags = list(set(tuple(flags) + tuple(extra_flags or ()) + tuple(config.extra_flags or ())))
    if config.dns_over_https:
        flags = list(flags) + ["--dns-over-https-templates=https://cloudflare-dns.com/dns-query"]
    if config.locale:
        base_lang = config.locale.split("-")[0].lower()
        accept_lang = f"{config.locale},{base_lang}" if base_lang != config.locale.lower() else config.locale
        flags = list(flags) + [f"--lang={config.locale}", f"--accept-lang={accept_lang}"]
    self._browser_options.update(
        {"args": flags, "headless": config.headless, "channel": "chrome" if config.real_chrome else "chromium"}
    )
    if config.executable_path:
        self._browser_options["executable_path"] = config.executable_path
    self._user_data_dir = config.user_data_dir

__validate__

__validate__(**params)
Código fuente en scrapling/engines/_browsers/_base.py
def __validate__(self, **params):
    self._config = self.__validate_routine__(params, model=self._config_class)
    self._context_options.update(
        {
            "is_mobile": False,
            "has_touch": False,
            # I'm thinking about disabling it to rest from all Service Workers' headache, but let's keep it as it is for now
            "service_workers": "allow",
            "ignore_https_errors": True,
            "screen": {"width": 1920, "height": 1080},
            "viewport": {"width": 1920, "height": 1080},
            "permissions": ["geolocation", "notifications"],
        }
    )
    self.__generate_stealth_options()

save_state async

save_state(path)

Guarda las cookies, el almacenamiento local e IndexedDB en un archivo JSON compatible con Playwright.

Requiere una sesión iniciada sin rotación de proxies. No guarda sessionStorage.

Código fuente en scrapling/engines/_browsers/_base.py
async def save_state(self, path: str | Path) -> None:
    """Save cookies, local storage and IndexedDB to a Playwright-compatible JSON file.

    Requires a started session without proxy rotation. Does not save sessionStorage.
    """
    if not self._is_alive or self.context is None:
        raise RuntimeError("Session state requires a started browser session without proxy rotation")
    await self.context.storage_state(path=Path(path), indexed_db=True)

load_state async

load_state(path)

Sustituye las cookies, el almacenamiento local e IndexedDB por los datos de un archivo JSON compatible con Playwright.

Requiere una sesión iniciada sin rotación de proxies. Carga o recarga las páginas para usar el inicio de sesión restaurado.

Código fuente en scrapling/engines/_browsers/_base.py
async def load_state(self, path: str | Path) -> None:
    """Replace cookies, local storage and IndexedDB from a Playwright-compatible JSON file.

    Requires a started session without proxy rotation. Fetch or reload pages to use the restored login.
    """
    if not self._is_alive or self.context is None:
        raise RuntimeError("Session state requires a started browser session without proxy rotation")
    await self.context.set_storage_state(path)

close_pages async

close_pages()

Cierra todas las pestañas del grupo de la sesión. La siguiente solicitud abre una pestaña nueva.

Código fuente en scrapling/engines/_browsers/_base.py
async def close_pages(self) -> None:
    """Close every open tab in the session's pool. The next request opens a fresh tab."""
    for page_info in self.page_pool.clear():
        with suppress(Exception):
            await cast(AsyncPage, page_info.page).close()

close async

close()

Cierra todos los recursos.

Código fuente en scrapling/engines/_browsers/_base.py
async def close(self):
    """Close all resources"""
    self.network._detach()
    if not self._is_alive:  # pragma: no cover
        return

    await self.close_pages()
    try:
        if self.context and self._owns_context:
            await self.context.close()
    finally:
        self.context = None
        try:
            if self.browser:
                await self.browser.close()
        finally:
            self.browser = None
            try:
                if self.playwright:
                    await self.playwright.stop()
            finally:
                self.playwright = None
                self._is_alive = False

__aenter__ async

__aenter__()
Código fuente en scrapling/engines/_browsers/_base.py
async def __aenter__(self):
    await self.start()
    return self

__aexit__ async

__aexit__(exc_type, exc_val, exc_tb)
Código fuente en scrapling/engines/_browsers/_base.py
async def __aexit__(self, exc_type, exc_val, exc_tb):
    await self.close()

get_pool_stats

get_pool_stats()

Obtiene estadísticas del grupo de páginas actual.

Código fuente en scrapling/engines/_browsers/_base.py
def get_pool_stats(self) -> Dict[str, int]:
    """Get statistics about the current page pool"""
    return {
        "total_pages": self.page_pool.pages_count,
        "busy_pages": self.page_pool.busy_count,
        "max_pages": self.max_pages,
    }

start async

start()

Crea un navegador para esta instancia y su contexto.

Código fuente en scrapling/engines/_browsers/_stealth.py
async def start(self) -> None:
    """Create a browser for this instance and context."""
    if not self.playwright:
        self.playwright = await async_playwright().start()
        self._is_alive = True
        try:
            await self._create_context()
            if self.context:
                self.context = await self._initialize_context(self._config, self.context)
        except BaseException:
            with suppress(Exception):
                await self.close()
            raise
    else:
        raise RuntimeError("Session has been already started")

fetch async

fetch(url, **kwargs)

Abre el navegador y realiza la solicitud con las opciones elegidas.

PARÁMETRO DESCRIPCIÓN
url

URL de destino.

TIPO: str

google_search

Está activado de forma predeterminada. Scrapling añade una cabecera referer de Google.

timeout

Tiempo máximo, en milisegundos, para todas las operaciones y esperas de la página. El valor predeterminado es 30 000.

wait

Tiempo en milisegundos que espera el fetcher cuando todo ha terminado, antes de cerrar la página y devolver el objeto Response.

page_action

Función para automatizar tareas. Recibe el objeto page y se ejecuta después de la navegación.

page_setup

Función que recibe el objeto page y se ejecuta antes de navegar. Úsala para registrar eventos o rutas que deban estar listos antes de cargar la página.

extra_headers

Diccionario de cabeceras adicionales para la solicitud. El referer de google_search tiene prioridad sobre el que definas aquí si usas ambos.

disable_resources

Descarta solicitudes de recursos innecesarios para mejorar la velocidad. Se descartan los tipos font, image, media, beacon, object, imageset, texttrack, websocket, csp_report y stylesheet.

blocked_domains

Conjunto de dominios cuyas solicitudes se bloquean. También incluye sus subdominios: por ejemplo, "example.com" bloquea "sub.example.com".

wait_selector

Espera a que un selector CSS concreto esté en el estado indicado.

wait_selector_state

Estado que debe alcanzar el selector indicado en wait_selector. El valor predeterminado es attached.

network_idle

Espera hasta que la página lleve al menos 500 ms sin conexiones de red.

load_dom

Está activado de forma predeterminada. Espera a que todo el JavaScript de las páginas se cargue y se ejecute.

pierce_shadow

Incluye el contenido del Shadow DOM abierto en el HTML de la respuesta. El valor predeterminado es False.

solve_cloudflare

Resuelve los distintos tipos de desafíos Turnstile e Interstitial de Cloudflare antes de devolver la respuesta.

selector_config

Argumentos que se pasan al crear la clase Selector final.

proxy

Proxy fijo que sustituye al rotador y al proxy de la sesión. Se crea un nuevo contexto de navegador para usarlo.

DEVUELVE DESCRIPCIÓN
Response

Objeto Response.

Código fuente en scrapling/engines/_browsers/_stealth.py
async def fetch(self, url: str, **kwargs: Unpack[StealthFetchParams]) -> Response:
    """Opens up the browser and do your request based on your chosen options.

    :param url: The Target url.
    :param google_search: Enabled by default, Scrapling will set a Google referer header.
    :param timeout: The timeout in milliseconds that is used in all operations and waits through the page. The default is 30,000
    :param wait: The time (milliseconds) the fetcher will wait after everything finishes before closing the page and returning the ` Response ` object.
    :param page_action: Added for automation. A function that takes the `page` object, runs after navigation, and does the automation you need.
    :param page_setup: A function that takes the `page` object, runs before navigation. Use it to register event listeners or routes that must be set up before the page loads.
    :param extra_headers: A dictionary of extra headers to add to the request. _The referer set by `google_search` takes priority over the referer set here if used together._
    :param disable_resources: Drop requests for unnecessary resources for a speed boost.
        Requests dropped are of type `font`, `image`, `media`, `beacon`, `object`, `imageset`, `texttrack`, `websocket`, `csp_report`, and `stylesheet`.
    :param blocked_domains: A set of domain names to block requests to. Subdomains are also matched (e.g., ``"example.com"`` blocks ``"sub.example.com"`` too).
    :param wait_selector: Wait for a specific CSS selector to be in a specific state.
    :param wait_selector_state: The state to wait for the selector given with `wait_selector`. The default state is `attached`.
    :param network_idle: Wait for the page until there are no network connections for at least 500 ms.
    :param load_dom: Enabled by default, wait for all JavaScript on page(s) to fully load and execute.
    :param pierce_shadow: Include open Shadow DOM content in the response HTML. Defaults to False.
    :param solve_cloudflare: Solves all types of the Cloudflare's Turnstile/Interstitial challenges before returning the response to you.
    :param selector_config: The arguments that will be passed in the end while creating the final Selector's class.
    :param proxy: Static proxy to override rotator and session proxy. A new browser context will be created and used with it.
    :return: A `Response` object.
    """
    static_proxy = kwargs.pop("proxy", None)
    if not self._owns_context:
        static_proxy = None

    params = _validate(kwargs, self, StealthConfig)

    if not self._is_alive:  # pragma: no cover
        raise RuntimeError("Context manager has been closed")

    request_headers_keys = {h.lower() for h in params.extra_headers.keys()} if params.extra_headers else set()
    referer = (
        "https://www.google.com/" if (params.google_search and "referer" not in request_headers_keys) else None
    )

    for attempt in range(self._config.retries):
        proxy: Optional[ProxyType] = None
        if self._config.proxy_rotator and static_proxy is None:
            proxy = self._config.proxy_rotator.get_proxy()
        else:
            proxy = static_proxy

        async with self._page_generator(
            params.timeout, params.extra_headers, params.disable_resources, proxy, params.blocked_domains
        ) as page_info:
            final_response: List = [None]
            page = page_info.page
            handler = self._create_response_handler(page_info, final_response)
            page.on("response", handler)
            try:
                if params.page_setup:
                    try:
                        await params.page_setup(page)
                    except Exception as e:  # pragma: no cover
                        log.error(f"Error executing page_setup: {e}")

                try:
                    first_response = await page.goto(url, referer=referer)
                    await self._wait_for_page_stability(page, params.load_dom, params.network_idle)

                    if not first_response:
                        raise RuntimeError(f"Failed to get response for {url}")

                    if params.solve_cloudflare:
                        await self._cloudflare_solver(page)
                        # Make sure the page is fully loaded after the captcha
                        await self._wait_for_page_stability(page, params.load_dom, params.network_idle)

                    if params.page_action:
                        try:
                            _ = await params.page_action(page)
                        except Exception as e:  # pragma: no cover
                            log.error(f"Error executing page_action: {e}")

                    if params.wait_selector:
                        try:
                            waiter: AsyncLocator = page.locator(params.wait_selector)
                            await waiter.first.wait_for(state=params.wait_selector_state)
                            await self._wait_for_page_stability(page, params.load_dom, params.network_idle)
                        except Exception as e:  # pragma: no cover
                            log.error(f"Error waiting for selector {params.wait_selector}: {e}")

                    await page.wait_for_timeout(params.wait)

                    response = await ResponseFactory.from_async_playwright_response(
                        page,
                        first_response,
                        final_response[0],
                        params.selector_config,
                        meta={"proxy": proxy},
                        pierce_shadow=params.pierce_shadow,
                    )
                    return response

                except Exception as e:
                    page_info.mark_error()
                    if attempt < self._config.retries - 1:
                        if is_proxy_error(e):
                            log.warning(
                                f"Proxy '{proxy}' failed (attempt {attempt + 1}) | Retrying in {self._config.retry_delay}s..."
                            )
                        else:
                            log.warning(
                                f"Attempt {attempt + 1} failed: {e}. Retrying in {self._config.retry_delay}s..."
                            )
                        await asyncio_sleep(self._config.retry_delay)
                    else:
                        log.error(f"Failed after {self._config.retries} attempts: {e}")
                        raise
            finally:
                page.remove_listener("response", handler)

    raise RuntimeError("Request failed")  # pragma: no cover

Sesiones remotas

scrapling.fetchers.RemoteSession

RemoteSession(cdp_url, *, new_context=True, **kwargs)

Clases base: _RemoteSessionMixin, StealthySession


              flowchart TD
              scrapling.fetchers.RemoteSession[RemoteSession]
              scrapling.engines._browsers._remote._RemoteSessionMixin[_RemoteSessionMixin]
              scrapling.engines._browsers._stealth.StealthySession[StealthySession]
              scrapling.engines._browsers._base.SyncSession[SyncSession]
              scrapling.engines._browsers._base.StealthySessionMixin[StealthySessionMixin]
              scrapling.engines._browsers._base.BaseSessionMixin[BaseSessionMixin]

                              scrapling.engines._browsers._remote._RemoteSessionMixin --> scrapling.fetchers.RemoteSession
                                scrapling.engines._browsers._base.StealthySessionMixin --> scrapling.engines._browsers._remote._RemoteSessionMixin
                                scrapling.engines._browsers._base.BaseSessionMixin --> scrapling.engines._browsers._base.StealthySessionMixin
                


                scrapling.engines._browsers._stealth.StealthySession --> scrapling.fetchers.RemoteSession
                                scrapling.engines._browsers._base.SyncSession --> scrapling.engines._browsers._stealth.StealthySession
                
                scrapling.engines._browsers._base.StealthySessionMixin --> scrapling.engines._browsers._stealth.StealthySession
                                scrapling.engines._browsers._base.BaseSessionMixin --> scrapling.engines._browsers._base.StealthySessionMixin
                




              click scrapling.fetchers.RemoteSession href "" "scrapling.fetchers.RemoteSession"
              click scrapling.engines._browsers._remote._RemoteSessionMixin href "" "scrapling.engines._browsers._remote._RemoteSessionMixin"
              click scrapling.engines._browsers._stealth.StealthySession href "" "scrapling.engines._browsers._stealth.StealthySession"
              click scrapling.engines._browsers._base.SyncSession href "" "scrapling.engines._browsers._base.SyncSession"
              click scrapling.engines._browsers._base.StealthySessionMixin href "" "scrapling.engines._browsers._base.StealthySessionMixin"
              click scrapling.engines._browsers._base.BaseSessionMixin href "" "scrapling.engines._browsers._base.BaseSessionMixin"
            

A CDP browser session that creates its own context or borrows the default context.

Gestor de sesiones de navegador con un grupo de páginas reutilizables. De forma predeterminada, usa un contexto persistente y un directorio temporal para el perfil de usuario.

PARÁMETRO DESCRIPCIÓN
record_requests

Guarda las solicitudes y respuestas del navegador que han terminado. Omite las fallidas y las pendientes. El valor predeterminado es False.

max_recorded_requests

Número máximo de solicitudes guardadas por sesión. El valor predeterminado es 1000. Se eliminan las entradas más antiguas.

headless

Ejecuta el navegador sin ventana visible, de forma predeterminada, o con una ventana visible.

disable_resources

Descarta solicitudes de recursos innecesarios para mejorar la velocidad. Se descartan los tipos font, image, media, beacon, object, imageset, texttrack, websocket, csp_report y stylesheet.

blocked_domains

Conjunto de dominios cuyas solicitudes se bloquean. También incluye sus subdominios: por ejemplo, "example.com" bloquea "sub.example.com".

useragent

Cadena User-Agent que se va a usar. Si no se indica, el fetcher genera una propia de un navegador real del mismo tipo.

cookies

Cookies que se usan en la siguiente solicitud.

network_idle

Espera hasta que la página lleve al menos 500 ms sin conexiones de red.

timeout

Tiempo máximo, en milisegundos, para todas las operaciones y esperas de la página. El valor predeterminado es 30 000.

wait

Tiempo en milisegundos que espera el fetcher cuando todo ha terminado, antes de cerrar la página y devolver el objeto Response.

page_action

Función para automatizar tareas. Recibe el objeto page y se ejecuta después de la navegación.

page_setup

Función que recibe el objeto page y se ejecuta antes de navegar. Úsala para registrar eventos o rutas que deban estar listos antes de cargar la página.

wait_selector

Espera a que un selector CSS concreto esté en el estado indicado.

init_script

Ruta absoluta a un archivo JavaScript que se ejecuta al crear cada página de esta sesión.

locale

Configuración regional del usuario, por ejemplo en-GB o de-DE. Afecta a navigator.language, a la cabecera Accept-Language y al formato de números y fechas. De forma predeterminada, usa la del sistema.

timezone_id

Cambia la zona horaria del navegador. De forma predeterminada, usa la del sistema.

wait_selector_state

Estado que debe alcanzar el selector indicado en wait_selector. El valor predeterminado es attached.

solve_cloudflare

Resuelve los distintos tipos de desafíos Turnstile e Interstitial de Cloudflare antes de devolver la respuesta.

real_chrome

Si tienes Chrome instalado, activa esta opción para que el fetcher abra y use una instancia de ese navegador.

hide_canvas

Añade ruido aleatorio a las operaciones de canvas para evitar que se identifique la huella del navegador.

block_webrtc

Obliga a WebRTC a respetar la configuración del proxy para evitar que se filtre la IP local.

allow_webgl

Está activado de forma predeterminada. Si lo desactivas, se deshabilitan WebGL y WebGL 2.0 por completo. No se recomienda hacerlo porque muchos WAF comprueban si WebGL está activo.

load_dom

Está activado de forma predeterminada. Espera a que todo el JavaScript de las páginas se cargue y se ejecute.

pierce_shadow

Incluye el contenido del Shadow DOM abierto en el HTML de la respuesta. El valor predeterminado es False.

google_search

Está activado de forma predeterminada. Scrapling añade una cabecera referer de Google.

extra_headers

Diccionario de cabeceras adicionales para la solicitud. El referer de google_search tiene prioridad sobre el que definas aquí si usas ambos.

proxy

Proxy que se usa en las solicitudes. Puede ser una cadena o un diccionario solo con las claves 'server', 'username' y 'password'.

user_data_dir

Ruta al directorio de datos del usuario, que guarda las cookies y el almacenamiento local del navegador. De forma predeterminada, se crea un directorio temporal.

extra_flags

Lista de opciones adicionales que se pasan al navegador al iniciarlo.

selector_config

Argumentos que se pasan al crear la clase Selector final.

additional_args

Opciones adicionales para el contexto de Playwright. Tienen prioridad sobre la configuración de Scrapling.

Connect to a remote browser when the session starts.

cdp_url

HTTP or WebSocket CDP endpoint of an existing Chromium browser.

TIPO: str

new_context

Create and close a separate context. If False, keep the existing default context open and ignore useragent, locale, timezone_id, proxy, proxy_rotator and additional_args.

TIPO: bool PREDETERMINADO: True

kwargs

Shared session and page options. Browser launch options do not apply. Cookies and init scripts affect the shared context when new_context is False.

TIPO: Unpack[RemoteSessionParams] PREDETERMINADO: {}

Código fuente en scrapling/engines/_browsers/_remote.py
def __init__(self, cdp_url: str, *, new_context: bool = True, **kwargs: Unpack[RemoteSessionParams]):
    """Connect to a remote browser when the session starts.

    :param cdp_url: HTTP or WebSocket CDP endpoint of an existing Chromium browser.
    :param new_context: Create and close a separate context. If False, keep the existing default context open
        and ignore useragent, locale, timezone_id, proxy, proxy_rotator and additional_args.
    :param kwargs: Shared session and page options. Browser launch options do not apply.
        Cookies and init scripts affect the shared context when new_context is False.
    """
    params: Dict[str, Any] = dict(kwargs, cdp_url=cdp_url, new_context=new_context)
    super().__init__(**params)
    self._owns_context = self._config.new_context

max_pages instance-attribute

max_pages = max_pages

network instance-attribute

network = NetworkRecorder(
    enabled=record_requests,
    max_requests=max_recorded_requests,
)

page_pool instance-attribute

page_pool = PagePool(max_pages)

playwright instance-attribute

playwright = None

context instance-attribute

context = None

browser instance-attribute

browser = None

__slots__ class-attribute instance-attribute

__slots__ = (
    "_config",
    "_context_options",
    "_browser_options",
    "_user_data_dir",
    "_headers_keys",
    "max_pages",
    "page_pool",
    "_max_wait_for_page",
    "playwright",
    "context",
)

__validate_routine__

__validate_routine__(params, model)
Código fuente en scrapling/engines/_browsers/_base.py
def __validate_routine__(
    self, params: Dict, model: type[PlaywrightConfig] | type[StealthConfig]
) -> PlaywrightConfig | StealthConfig:
    # Dark color scheme bypasses the 'prefersLightColor' check in creepjs
    self._context_options: Dict[str, Any] = {"color_scheme": "dark", "device_scale_factor": 2}
    self._browser_options: Dict[str, Any] = {
        "args": DEFAULT_ARGS,
        "ignore_default_args": HARMFUL_ARGS,
    }
    if "__max_pages" in params:
        params["max_pages"] = params.pop("__max_pages")

    config = validate(params, model=model)
    self._headers_keys = (
        {header.lower() for header in config.extra_headers.keys()} if config.extra_headers else set()
    )

    return config

__generate_context_options__

__generate_context_options__()
Código fuente en scrapling/engines/_browsers/_base.py
def __generate_context_options__(self) -> None:
    config: PlaywrightConfig | StealthConfig = self._config
    self._context_options.update(
        {
            "proxy": config.proxy,
            "timezone_id": config.timezone_id,
            "extra_http_headers": config.extra_headers,
        }
    )
    # The default useragent in the headful is always correct now in the current versions of Playwright
    if config.useragent:
        self._context_options["user_agent"] = config.useragent
    elif not config.useragent and config.headless:
        self._context_options["user_agent"] = (
            __default_chrome_useragent__ if config.real_chrome else __default_useragent__
        )

    if config.additional_args:
        self._context_options.update(config.additional_args)

__generate_options__

__generate_options__(extra_flags=None)
Código fuente en scrapling/engines/_browsers/_remote.py
def __generate_options__(self, extra_flags: Tuple | None = None) -> None:
    self._browser_options = {}
    if self._config.new_context:
        if self._config.locale:
            self._context_options["locale"] = self._config.locale
        self.__generate_context_options__()
    else:
        self._context_options = {}

__validate__

__validate__(**params)
Código fuente en scrapling/engines/_browsers/_base.py
def __validate__(self, **params):
    self._config = self.__validate_routine__(params, model=self._config_class)
    self._context_options.update(
        {
            "is_mobile": False,
            "has_touch": False,
            # I'm thinking about disabling it to rest from all Service Workers' headache, but let's keep it as it is for now
            "service_workers": "allow",
            "ignore_https_errors": True,
            "screen": {"width": 1920, "height": 1080},
            "viewport": {"width": 1920, "height": 1080},
            "permissions": ["geolocation", "notifications"],
        }
    )
    self.__generate_stealth_options()

start

start()

Crea un navegador para esta instancia y su contexto.

Código fuente en scrapling/engines/_browsers/_stealth.py
def start(self) -> None:
    """Create a browser for this instance and context."""
    if not self.playwright:
        self.playwright = sync_playwright().start()
        self._is_alive = True
        try:
            self._create_context()
            if self.context:
                self.context = self._initialize_context(self._config, self.context)
        except BaseException:
            with suppress(Exception):
                self.close()
            raise
    else:
        raise RuntimeError("Session has been already started")

save_state

save_state(path)

Guarda las cookies, el almacenamiento local e IndexedDB en un archivo JSON compatible con Playwright.

Requiere una sesión iniciada sin rotación de proxies. No guarda sessionStorage.

Código fuente en scrapling/engines/_browsers/_base.py
def save_state(self, path: str | Path) -> None:
    """Save cookies, local storage and IndexedDB to a Playwright-compatible JSON file.

    Requires a started session without proxy rotation. Does not save sessionStorage.
    """
    if not self._is_alive or self.context is None:
        raise RuntimeError("Session state requires a started browser session without proxy rotation")
    self.context.storage_state(path=Path(path), indexed_db=True)

load_state

load_state(path)

Sustituye las cookies, el almacenamiento local e IndexedDB por los datos de un archivo JSON compatible con Playwright.

Requiere una sesión iniciada sin rotación de proxies. Carga o recarga las páginas para usar el inicio de sesión restaurado.

Código fuente en scrapling/engines/_browsers/_base.py
def load_state(self, path: str | Path) -> None:
    """Replace cookies, local storage and IndexedDB from a Playwright-compatible JSON file.

    Requires a started session without proxy rotation. Fetch or reload pages to use the restored login.
    """
    if not self._is_alive or self.context is None:
        raise RuntimeError("Session state requires a started browser session without proxy rotation")
    self.context.set_storage_state(path)

close_pages

close_pages()

Cierra todas las pestañas del grupo de la sesión. La siguiente solicitud abre una pestaña nueva.

Código fuente en scrapling/engines/_browsers/_base.py
def close_pages(self) -> None:
    """Close every open tab in the session's pool. The next request opens a fresh tab."""
    for page_info in self.page_pool.clear():
        with suppress(Exception):
            page_info.page.close()

close

close()

Cierra todos los recursos.

Código fuente en scrapling/engines/_browsers/_base.py
def close(self):  # pragma: no cover
    """Close all resources"""
    self.network._detach()
    if not self._is_alive:
        return

    self.close_pages()
    try:
        if self.context and self._owns_context:
            self.context.close()
    finally:
        self.context = None
        try:
            if self.browser:
                self.browser.close()
        finally:
            self.browser = None
            try:
                if self.playwright:
                    self.playwright.stop()
            finally:
                self.playwright = None
                self._is_alive = False

__enter__

__enter__()
Código fuente en scrapling/engines/_browsers/_base.py
def __enter__(self):
    self.start()
    return self

__exit__

__exit__(exc_type, exc_val, exc_tb)
Código fuente en scrapling/engines/_browsers/_base.py
def __exit__(self, exc_type, exc_val, exc_tb):
    self.close()

get_pool_stats

get_pool_stats()

Obtiene estadísticas del grupo de páginas actual.

Código fuente en scrapling/engines/_browsers/_base.py
def get_pool_stats(self) -> Dict[str, int]:
    """Get statistics about the current page pool"""
    return {
        "total_pages": self.page_pool.pages_count,
        "busy_pages": self.page_pool.busy_count,
        "max_pages": self.max_pages,
    }

fetch

fetch(url, **kwargs)

Abre el navegador y realiza la solicitud con las opciones elegidas.

PARÁMETRO DESCRIPCIÓN
url

URL de destino.

TIPO: str

google_search

Está activado de forma predeterminada. Scrapling añade una cabecera referer de Google.

timeout

Tiempo máximo, en milisegundos, para todas las operaciones y esperas de la página. El valor predeterminado es 30 000.

wait

Tiempo en milisegundos que espera el fetcher cuando todo ha terminado, antes de cerrar la página y devolver el objeto Response.

page_action

Función para automatizar tareas. Recibe el objeto page y se ejecuta después de la navegación.

page_setup

Función que recibe el objeto page y se ejecuta antes de navegar. Úsala para registrar eventos o rutas que deban estar listos antes de cargar la página.

extra_headers

Diccionario de cabeceras adicionales para la solicitud. El referer de google_search tiene prioridad sobre el que definas aquí si usas ambos.

disable_resources

Descarta solicitudes de recursos innecesarios para mejorar la velocidad. Se descartan los tipos font, image, media, beacon, object, imageset, texttrack, websocket, csp_report y stylesheet.

blocked_domains

Conjunto de dominios cuyas solicitudes se bloquean. También incluye sus subdominios: por ejemplo, "example.com" bloquea "sub.example.com".

wait_selector

Espera a que un selector CSS concreto esté en el estado indicado.

wait_selector_state

Estado que debe alcanzar el selector indicado en wait_selector. El valor predeterminado es attached.

network_idle

Espera hasta que la página lleve al menos 500 ms sin conexiones de red.

load_dom

Está activado de forma predeterminada. Espera a que todo el JavaScript de las páginas se cargue y se ejecute.

pierce_shadow

Incluye el contenido del Shadow DOM abierto en el HTML de la respuesta. El valor predeterminado es False.

solve_cloudflare

Resuelve los distintos tipos de desafíos Turnstile e Interstitial de Cloudflare antes de devolver la respuesta.

selector_config

Argumentos que se pasan al crear la clase Selector final.

proxy

Proxy fijo que sustituye al rotador y al proxy de la sesión. Se crea un nuevo contexto de navegador para usarlo.

DEVUELVE DESCRIPCIÓN
Response

Objeto Response.

Código fuente en scrapling/engines/_browsers/_stealth.py
def fetch(self, url: str, **kwargs: Unpack[StealthFetchParams]) -> Response:
    """Opens up the browser and do your request based on your chosen options.

    :param url: The Target url.
    :param google_search: Enabled by default, Scrapling will set a Google referer header.
    :param timeout: The timeout in milliseconds that is used in all operations and waits through the page. The default is 30,000
    :param wait: The time (milliseconds) the fetcher will wait after everything finishes before closing the page and returning the ` Response ` object.
    :param page_action: Added for automation. A function that takes the `page` object, runs after navigation, and does the automation you need.
    :param page_setup: A function that takes the `page` object, runs before navigation. Use it to register event listeners or routes that must be set up before the page loads.
    :param extra_headers: A dictionary of extra headers to add to the request. _The referer set by `google_search` takes priority over the referer set here if used together._
    :param disable_resources: Drop requests for unnecessary resources for a speed boost.
        Requests dropped are of type `font`, `image`, `media`, `beacon`, `object`, `imageset`, `texttrack`, `websocket`, `csp_report`, and `stylesheet`.
    :param blocked_domains: A set of domain names to block requests to. Subdomains are also matched (e.g., ``"example.com"`` blocks ``"sub.example.com"`` too).
    :param wait_selector: Wait for a specific CSS selector to be in a specific state.
    :param wait_selector_state: The state to wait for the selector given with `wait_selector`. The default state is `attached`.
    :param network_idle: Wait for the page until there are no network connections for at least 500 ms.
    :param load_dom: Enabled by default, wait for all JavaScript on page(s) to fully load and execute.
    :param pierce_shadow: Include open Shadow DOM content in the response HTML. Defaults to False.
    :param solve_cloudflare: Solves all types of the Cloudflare's Turnstile/Interstitial challenges before returning the response to you.
    :param selector_config: The arguments that will be passed in the end while creating the final Selector's class.
    :param proxy: Static proxy to override rotator and session proxy. A new browser context will be created and used with it.
    :return: A `Response` object.
    """
    static_proxy = kwargs.pop("proxy", None)
    if not self._owns_context:
        static_proxy = None

    params = _validate(kwargs, self, StealthConfig)
    if not self._is_alive:  # pragma: no cover
        raise RuntimeError("Context manager has been closed")

    request_headers_keys = {h.lower() for h in params.extra_headers.keys()} if params.extra_headers else set()
    referer = (
        "https://www.google.com/" if (params.google_search and "referer" not in request_headers_keys) else None
    )

    for attempt in range(self._config.retries):
        proxy: Optional[ProxyType] = None
        if self._config.proxy_rotator and static_proxy is None:
            proxy = self._config.proxy_rotator.get_proxy()
        else:
            proxy = static_proxy

        with self._page_generator(
            params.timeout, params.extra_headers, params.disable_resources, proxy, params.blocked_domains
        ) as page_info:
            final_response: List = [None]
            page = page_info.page
            handler = self._create_response_handler(page_info, final_response)
            page.on("response", handler)
            try:
                if params.page_setup:
                    try:
                        params.page_setup(page)
                    except Exception as e:  # pragma: no cover
                        log.error(f"Error executing page_setup: {e}")

                try:
                    first_response = page.goto(url, referer=referer)
                    self._wait_for_page_stability(page, params.load_dom, params.network_idle)

                    if not first_response:
                        raise RuntimeError(f"Failed to get response for {url}")

                    if params.solve_cloudflare:
                        self._cloudflare_solver(page)
                        # Make sure the page is fully loaded after the captcha
                        self._wait_for_page_stability(page, params.load_dom, params.network_idle)

                    if params.page_action:
                        try:
                            _ = params.page_action(page)
                        except Exception as e:  # pragma: no cover
                            log.error(f"Error executing page_action: {e}")

                    if params.wait_selector:
                        try:
                            waiter: Locator = page.locator(params.wait_selector)
                            waiter.first.wait_for(state=params.wait_selector_state)
                            self._wait_for_page_stability(page, params.load_dom, params.network_idle)
                        except Exception as e:  # pragma: no cover
                            log.error(f"Error waiting for selector {params.wait_selector}: {e}")

                    page.wait_for_timeout(params.wait)

                    response = ResponseFactory.from_playwright_response(
                        page,
                        first_response,
                        final_response[0],
                        params.selector_config,
                        meta={"proxy": proxy},
                        pierce_shadow=params.pierce_shadow,
                    )
                    return response

                except Exception as e:
                    page_info.mark_error()
                    if attempt < self._config.retries - 1:
                        if is_proxy_error(e):
                            log.warning(
                                f"Proxy '{proxy}' failed (attempt {attempt + 1}) | Retrying in {self._config.retry_delay}s..."
                            )
                        else:
                            log.warning(
                                f"Attempt {attempt + 1} failed: {e}. Retrying in {self._config.retry_delay}s..."
                            )
                        time_sleep(self._config.retry_delay)
                    else:
                        log.error(f"Failed after {self._config.retries} attempts: {e}")
                        raise
            finally:
                page.remove_listener("response", handler)

    raise RuntimeError("Request failed")  # pragma: no cover

scrapling.fetchers.AsyncRemoteSession

AsyncRemoteSession(cdp_url, *, new_context=True, **kwargs)

Clases base: _RemoteSessionMixin, AsyncStealthySession


              flowchart TD
              scrapling.fetchers.AsyncRemoteSession[AsyncRemoteSession]
              scrapling.engines._browsers._remote._RemoteSessionMixin[_RemoteSessionMixin]
              scrapling.engines._browsers._stealth.AsyncStealthySession[AsyncStealthySession]
              scrapling.engines._browsers._base.AsyncSession[AsyncSession]
              scrapling.engines._browsers._base.StealthySessionMixin[StealthySessionMixin]
              scrapling.engines._browsers._base.BaseSessionMixin[BaseSessionMixin]

                              scrapling.engines._browsers._remote._RemoteSessionMixin --> scrapling.fetchers.AsyncRemoteSession
                                scrapling.engines._browsers._base.StealthySessionMixin --> scrapling.engines._browsers._remote._RemoteSessionMixin
                                scrapling.engines._browsers._base.BaseSessionMixin --> scrapling.engines._browsers._base.StealthySessionMixin
                


                scrapling.engines._browsers._stealth.AsyncStealthySession --> scrapling.fetchers.AsyncRemoteSession
                                scrapling.engines._browsers._base.AsyncSession --> scrapling.engines._browsers._stealth.AsyncStealthySession
                
                scrapling.engines._browsers._base.StealthySessionMixin --> scrapling.engines._browsers._stealth.AsyncStealthySession
                                scrapling.engines._browsers._base.BaseSessionMixin --> scrapling.engines._browsers._base.StealthySessionMixin
                




              click scrapling.fetchers.AsyncRemoteSession href "" "scrapling.fetchers.AsyncRemoteSession"
              click scrapling.engines._browsers._remote._RemoteSessionMixin href "" "scrapling.engines._browsers._remote._RemoteSessionMixin"
              click scrapling.engines._browsers._stealth.AsyncStealthySession href "" "scrapling.engines._browsers._stealth.AsyncStealthySession"
              click scrapling.engines._browsers._base.AsyncSession href "" "scrapling.engines._browsers._base.AsyncSession"
              click scrapling.engines._browsers._base.StealthySessionMixin href "" "scrapling.engines._browsers._base.StealthySessionMixin"
              click scrapling.engines._browsers._base.BaseSessionMixin href "" "scrapling.engines._browsers._base.BaseSessionMixin"
            

An async CDP session that creates its own context or borrows the default context.

Gestor de sesiones de navegador con un grupo de páginas reutilizables. De forma predeterminada, usa un contexto persistente y un directorio temporal para el perfil de usuario.

PARÁMETRO DESCRIPCIÓN
record_requests

Guarda las solicitudes y respuestas del navegador que han terminado. Omite las fallidas y las pendientes. El valor predeterminado es False.

max_recorded_requests

Número máximo de solicitudes guardadas por sesión. El valor predeterminado es 1000. Se eliminan las entradas más antiguas.

headless

Ejecuta el navegador sin ventana visible, de forma predeterminada, o con una ventana visible.

disable_resources

Descarta solicitudes de recursos innecesarios para mejorar la velocidad. Se descartan los tipos font, image, media, beacon, object, imageset, texttrack, websocket, csp_report y stylesheet.

blocked_domains

Conjunto de dominios cuyas solicitudes se bloquean. También incluye sus subdominios: por ejemplo, "example.com" bloquea "sub.example.com".

useragent

Cadena User-Agent que se va a usar. Si no se indica, el fetcher genera una propia de un navegador real del mismo tipo.

cookies

Cookies que se usan en la siguiente solicitud.

network_idle

Espera hasta que la página lleve al menos 500 ms sin conexiones de red.

timeout

Tiempo máximo, en milisegundos, para todas las operaciones y esperas de la página. El valor predeterminado es 30 000.

wait

Tiempo en milisegundos que espera el fetcher cuando todo ha terminado, antes de cerrar la página y devolver el objeto Response.

page_action

Función para automatizar tareas. Recibe el objeto page y se ejecuta después de la navegación.

page_setup

Función que recibe el objeto page y se ejecuta antes de navegar. Úsala para registrar eventos o rutas que deban estar listos antes de cargar la página.

wait_selector

Espera a que un selector CSS concreto esté en el estado indicado.

init_script

Ruta absoluta a un archivo JavaScript que se ejecuta al crear cada página de esta sesión.

locale

Configuración regional del usuario, por ejemplo en-GB o de-DE. Afecta a navigator.language, a la cabecera Accept-Language y al formato de números y fechas. De forma predeterminada, usa la del sistema.

timezone_id

Cambia la zona horaria del navegador. De forma predeterminada, usa la del sistema.

wait_selector_state

Estado que debe alcanzar el selector indicado en wait_selector. El valor predeterminado es attached.

solve_cloudflare

Resuelve los distintos tipos de desafíos Turnstile e Interstitial de Cloudflare antes de devolver la respuesta.

real_chrome

Si tienes Chrome instalado, activa esta opción para que el fetcher abra y use una instancia de ese navegador.

hide_canvas

Añade ruido aleatorio a las operaciones de canvas para evitar que se identifique la huella del navegador.

block_webrtc

Obliga a WebRTC a respetar la configuración del proxy para evitar que se filtre la IP local.

allow_webgl

Está activado de forma predeterminada. Si lo desactivas, se deshabilitan WebGL y WebGL 2.0 por completo. No se recomienda hacerlo porque muchos WAF comprueban si WebGL está activo.

load_dom

Está activado de forma predeterminada. Espera a que todo el JavaScript de las páginas se cargue y se ejecute.

pierce_shadow

Incluye el contenido del Shadow DOM abierto en el HTML de la respuesta. El valor predeterminado es False.

google_search

Está activado de forma predeterminada. Scrapling añade una cabecera referer de Google.

extra_headers

Diccionario de cabeceras adicionales para la solicitud. El referer de google_search tiene prioridad sobre el que definas aquí si usas ambos.

proxy

Proxy que se usa en las solicitudes. Puede ser una cadena o un diccionario solo con las claves 'server', 'username' y 'password'.

user_data_dir

Ruta al directorio de datos del usuario, que guarda las cookies y el almacenamiento local del navegador. De forma predeterminada, se crea un directorio temporal.

extra_flags

Lista de opciones adicionales que se pasan al navegador al iniciarlo.

selector_config

Argumentos que se pasan al crear la clase Selector final.

additional_args

Opciones adicionales para el contexto de Playwright. Tienen prioridad sobre la configuración de Scrapling.

Connect to a remote browser when the session starts.

cdp_url

HTTP or WebSocket CDP endpoint of an existing Chromium browser.

TIPO: str

new_context

Create and close a separate context. If False, keep the existing default context open and ignore useragent, locale, timezone_id, proxy, proxy_rotator and additional_args.

TIPO: bool PREDETERMINADO: True

kwargs

Shared session and page options. Browser launch options do not apply. Cookies and init scripts affect the shared context when new_context is False.

TIPO: Unpack[RemoteSessionParams] PREDETERMINADO: {}

Código fuente en scrapling/engines/_browsers/_remote.py
def __init__(self, cdp_url: str, *, new_context: bool = True, **kwargs: Unpack[RemoteSessionParams]):
    """Connect to a remote browser when the session starts.

    :param cdp_url: HTTP or WebSocket CDP endpoint of an existing Chromium browser.
    :param new_context: Create and close a separate context. If False, keep the existing default context open
        and ignore useragent, locale, timezone_id, proxy, proxy_rotator and additional_args.
    :param kwargs: Shared session and page options. Browser launch options do not apply.
        Cookies and init scripts affect the shared context when new_context is False.
    """
    params: Dict[str, Any] = dict(kwargs, cdp_url=cdp_url, new_context=new_context)
    super().__init__(**params)
    self._owns_context = self._config.new_context

max_pages instance-attribute

max_pages = max_pages

network instance-attribute

network = NetworkRecorder(
    enabled=record_requests,
    max_requests=max_recorded_requests,
    asynchronous=True,
)

page_pool instance-attribute

page_pool = PagePool(max_pages)

playwright instance-attribute

playwright = None

context instance-attribute

context = None

browser instance-attribute

browser = None

__slots__ class-attribute instance-attribute

__slots__ = (
    "_config",
    "_context_options",
    "_browser_options",
    "_user_data_dir",
    "_headers_keys",
)

__validate_routine__

__validate_routine__(params, model)
Código fuente en scrapling/engines/_browsers/_base.py
def __validate_routine__(
    self, params: Dict, model: type[PlaywrightConfig] | type[StealthConfig]
) -> PlaywrightConfig | StealthConfig:
    # Dark color scheme bypasses the 'prefersLightColor' check in creepjs
    self._context_options: Dict[str, Any] = {"color_scheme": "dark", "device_scale_factor": 2}
    self._browser_options: Dict[str, Any] = {
        "args": DEFAULT_ARGS,
        "ignore_default_args": HARMFUL_ARGS,
    }
    if "__max_pages" in params:
        params["max_pages"] = params.pop("__max_pages")

    config = validate(params, model=model)
    self._headers_keys = (
        {header.lower() for header in config.extra_headers.keys()} if config.extra_headers else set()
    )

    return config

__generate_context_options__

__generate_context_options__()
Código fuente en scrapling/engines/_browsers/_base.py
def __generate_context_options__(self) -> None:
    config: PlaywrightConfig | StealthConfig = self._config
    self._context_options.update(
        {
            "proxy": config.proxy,
            "timezone_id": config.timezone_id,
            "extra_http_headers": config.extra_headers,
        }
    )
    # The default useragent in the headful is always correct now in the current versions of Playwright
    if config.useragent:
        self._context_options["user_agent"] = config.useragent
    elif not config.useragent and config.headless:
        self._context_options["user_agent"] = (
            __default_chrome_useragent__ if config.real_chrome else __default_useragent__
        )

    if config.additional_args:
        self._context_options.update(config.additional_args)

__generate_options__

__generate_options__(extra_flags=None)
Código fuente en scrapling/engines/_browsers/_remote.py
def __generate_options__(self, extra_flags: Tuple | None = None) -> None:
    self._browser_options = {}
    if self._config.new_context:
        if self._config.locale:
            self._context_options["locale"] = self._config.locale
        self.__generate_context_options__()
    else:
        self._context_options = {}

__validate__

__validate__(**params)
Código fuente en scrapling/engines/_browsers/_base.py
def __validate__(self, **params):
    self._config = self.__validate_routine__(params, model=self._config_class)
    self._context_options.update(
        {
            "is_mobile": False,
            "has_touch": False,
            # I'm thinking about disabling it to rest from all Service Workers' headache, but let's keep it as it is for now
            "service_workers": "allow",
            "ignore_https_errors": True,
            "screen": {"width": 1920, "height": 1080},
            "viewport": {"width": 1920, "height": 1080},
            "permissions": ["geolocation", "notifications"],
        }
    )
    self.__generate_stealth_options()

start async

start()

Crea un navegador para esta instancia y su contexto.

Código fuente en scrapling/engines/_browsers/_stealth.py
async def start(self) -> None:
    """Create a browser for this instance and context."""
    if not self.playwright:
        self.playwright = await async_playwright().start()
        self._is_alive = True
        try:
            await self._create_context()
            if self.context:
                self.context = await self._initialize_context(self._config, self.context)
        except BaseException:
            with suppress(Exception):
                await self.close()
            raise
    else:
        raise RuntimeError("Session has been already started")

save_state async

save_state(path)

Guarda las cookies, el almacenamiento local e IndexedDB en un archivo JSON compatible con Playwright.

Requiere una sesión iniciada sin rotación de proxies. No guarda sessionStorage.

Código fuente en scrapling/engines/_browsers/_base.py
async def save_state(self, path: str | Path) -> None:
    """Save cookies, local storage and IndexedDB to a Playwright-compatible JSON file.

    Requires a started session without proxy rotation. Does not save sessionStorage.
    """
    if not self._is_alive or self.context is None:
        raise RuntimeError("Session state requires a started browser session without proxy rotation")
    await self.context.storage_state(path=Path(path), indexed_db=True)

load_state async

load_state(path)

Sustituye las cookies, el almacenamiento local e IndexedDB por los datos de un archivo JSON compatible con Playwright.

Requiere una sesión iniciada sin rotación de proxies. Carga o recarga las páginas para usar el inicio de sesión restaurado.

Código fuente en scrapling/engines/_browsers/_base.py
async def load_state(self, path: str | Path) -> None:
    """Replace cookies, local storage and IndexedDB from a Playwright-compatible JSON file.

    Requires a started session without proxy rotation. Fetch or reload pages to use the restored login.
    """
    if not self._is_alive or self.context is None:
        raise RuntimeError("Session state requires a started browser session without proxy rotation")
    await self.context.set_storage_state(path)

close_pages async

close_pages()

Cierra todas las pestañas del grupo de la sesión. La siguiente solicitud abre una pestaña nueva.

Código fuente en scrapling/engines/_browsers/_base.py
async def close_pages(self) -> None:
    """Close every open tab in the session's pool. The next request opens a fresh tab."""
    for page_info in self.page_pool.clear():
        with suppress(Exception):
            await cast(AsyncPage, page_info.page).close()

close async

close()

Cierra todos los recursos.

Código fuente en scrapling/engines/_browsers/_base.py
async def close(self):
    """Close all resources"""
    self.network._detach()
    if not self._is_alive:  # pragma: no cover
        return

    await self.close_pages()
    try:
        if self.context and self._owns_context:
            await self.context.close()
    finally:
        self.context = None
        try:
            if self.browser:
                await self.browser.close()
        finally:
            self.browser = None
            try:
                if self.playwright:
                    await self.playwright.stop()
            finally:
                self.playwright = None
                self._is_alive = False

__aenter__ async

__aenter__()
Código fuente en scrapling/engines/_browsers/_base.py
async def __aenter__(self):
    await self.start()
    return self

__aexit__ async

__aexit__(exc_type, exc_val, exc_tb)
Código fuente en scrapling/engines/_browsers/_base.py
async def __aexit__(self, exc_type, exc_val, exc_tb):
    await self.close()

get_pool_stats

get_pool_stats()

Obtiene estadísticas del grupo de páginas actual.

Código fuente en scrapling/engines/_browsers/_base.py
def get_pool_stats(self) -> Dict[str, int]:
    """Get statistics about the current page pool"""
    return {
        "total_pages": self.page_pool.pages_count,
        "busy_pages": self.page_pool.busy_count,
        "max_pages": self.max_pages,
    }

fetch async

fetch(url, **kwargs)

Abre el navegador y realiza la solicitud con las opciones elegidas.

PARÁMETRO DESCRIPCIÓN
url

URL de destino.

TIPO: str

google_search

Está activado de forma predeterminada. Scrapling añade una cabecera referer de Google.

timeout

Tiempo máximo, en milisegundos, para todas las operaciones y esperas de la página. El valor predeterminado es 30 000.

wait

Tiempo en milisegundos que espera el fetcher cuando todo ha terminado, antes de cerrar la página y devolver el objeto Response.

page_action

Función para automatizar tareas. Recibe el objeto page y se ejecuta después de la navegación.

page_setup

Función que recibe el objeto page y se ejecuta antes de navegar. Úsala para registrar eventos o rutas que deban estar listos antes de cargar la página.

extra_headers

Diccionario de cabeceras adicionales para la solicitud. El referer de google_search tiene prioridad sobre el que definas aquí si usas ambos.

disable_resources

Descarta solicitudes de recursos innecesarios para mejorar la velocidad. Se descartan los tipos font, image, media, beacon, object, imageset, texttrack, websocket, csp_report y stylesheet.

blocked_domains

Conjunto de dominios cuyas solicitudes se bloquean. También incluye sus subdominios: por ejemplo, "example.com" bloquea "sub.example.com".

wait_selector

Espera a que un selector CSS concreto esté en el estado indicado.

wait_selector_state

Estado que debe alcanzar el selector indicado en wait_selector. El valor predeterminado es attached.

network_idle

Espera hasta que la página lleve al menos 500 ms sin conexiones de red.

load_dom

Está activado de forma predeterminada. Espera a que todo el JavaScript de las páginas se cargue y se ejecute.

pierce_shadow

Incluye el contenido del Shadow DOM abierto en el HTML de la respuesta. El valor predeterminado es False.

solve_cloudflare

Resuelve los distintos tipos de desafíos Turnstile e Interstitial de Cloudflare antes de devolver la respuesta.

selector_config

Argumentos que se pasan al crear la clase Selector final.

proxy

Proxy fijo que sustituye al rotador y al proxy de la sesión. Se crea un nuevo contexto de navegador para usarlo.

DEVUELVE DESCRIPCIÓN
Response

Objeto Response.

Código fuente en scrapling/engines/_browsers/_stealth.py
async def fetch(self, url: str, **kwargs: Unpack[StealthFetchParams]) -> Response:
    """Opens up the browser and do your request based on your chosen options.

    :param url: The Target url.
    :param google_search: Enabled by default, Scrapling will set a Google referer header.
    :param timeout: The timeout in milliseconds that is used in all operations and waits through the page. The default is 30,000
    :param wait: The time (milliseconds) the fetcher will wait after everything finishes before closing the page and returning the ` Response ` object.
    :param page_action: Added for automation. A function that takes the `page` object, runs after navigation, and does the automation you need.
    :param page_setup: A function that takes the `page` object, runs before navigation. Use it to register event listeners or routes that must be set up before the page loads.
    :param extra_headers: A dictionary of extra headers to add to the request. _The referer set by `google_search` takes priority over the referer set here if used together._
    :param disable_resources: Drop requests for unnecessary resources for a speed boost.
        Requests dropped are of type `font`, `image`, `media`, `beacon`, `object`, `imageset`, `texttrack`, `websocket`, `csp_report`, and `stylesheet`.
    :param blocked_domains: A set of domain names to block requests to. Subdomains are also matched (e.g., ``"example.com"`` blocks ``"sub.example.com"`` too).
    :param wait_selector: Wait for a specific CSS selector to be in a specific state.
    :param wait_selector_state: The state to wait for the selector given with `wait_selector`. The default state is `attached`.
    :param network_idle: Wait for the page until there are no network connections for at least 500 ms.
    :param load_dom: Enabled by default, wait for all JavaScript on page(s) to fully load and execute.
    :param pierce_shadow: Include open Shadow DOM content in the response HTML. Defaults to False.
    :param solve_cloudflare: Solves all types of the Cloudflare's Turnstile/Interstitial challenges before returning the response to you.
    :param selector_config: The arguments that will be passed in the end while creating the final Selector's class.
    :param proxy: Static proxy to override rotator and session proxy. A new browser context will be created and used with it.
    :return: A `Response` object.
    """
    static_proxy = kwargs.pop("proxy", None)
    if not self._owns_context:
        static_proxy = None

    params = _validate(kwargs, self, StealthConfig)

    if not self._is_alive:  # pragma: no cover
        raise RuntimeError("Context manager has been closed")

    request_headers_keys = {h.lower() for h in params.extra_headers.keys()} if params.extra_headers else set()
    referer = (
        "https://www.google.com/" if (params.google_search and "referer" not in request_headers_keys) else None
    )

    for attempt in range(self._config.retries):
        proxy: Optional[ProxyType] = None
        if self._config.proxy_rotator and static_proxy is None:
            proxy = self._config.proxy_rotator.get_proxy()
        else:
            proxy = static_proxy

        async with self._page_generator(
            params.timeout, params.extra_headers, params.disable_resources, proxy, params.blocked_domains
        ) as page_info:
            final_response: List = [None]
            page = page_info.page
            handler = self._create_response_handler(page_info, final_response)
            page.on("response", handler)
            try:
                if params.page_setup:
                    try:
                        await params.page_setup(page)
                    except Exception as e:  # pragma: no cover
                        log.error(f"Error executing page_setup: {e}")

                try:
                    first_response = await page.goto(url, referer=referer)
                    await self._wait_for_page_stability(page, params.load_dom, params.network_idle)

                    if not first_response:
                        raise RuntimeError(f"Failed to get response for {url}")

                    if params.solve_cloudflare:
                        await self._cloudflare_solver(page)
                        # Make sure the page is fully loaded after the captcha
                        await self._wait_for_page_stability(page, params.load_dom, params.network_idle)

                    if params.page_action:
                        try:
                            _ = await params.page_action(page)
                        except Exception as e:  # pragma: no cover
                            log.error(f"Error executing page_action: {e}")

                    if params.wait_selector:
                        try:
                            waiter: AsyncLocator = page.locator(params.wait_selector)
                            await waiter.first.wait_for(state=params.wait_selector_state)
                            await self._wait_for_page_stability(page, params.load_dom, params.network_idle)
                        except Exception as e:  # pragma: no cover
                            log.error(f"Error waiting for selector {params.wait_selector}: {e}")

                    await page.wait_for_timeout(params.wait)

                    response = await ResponseFactory.from_async_playwright_response(
                        page,
                        first_response,
                        final_response[0],
                        params.selector_config,
                        meta={"proxy": proxy},
                        pierce_shadow=params.pierce_shadow,
                    )
                    return response

                except Exception as e:
                    page_info.mark_error()
                    if attempt < self._config.retries - 1:
                        if is_proxy_error(e):
                            log.warning(
                                f"Proxy '{proxy}' failed (attempt {attempt + 1}) | Retrying in {self._config.retry_delay}s..."
                            )
                        else:
                            log.warning(
                                f"Attempt {attempt + 1} failed: {e}. Retrying in {self._config.retry_delay}s..."
                            )
                        await asyncio_sleep(self._config.retry_delay)
                    else:
                        log.error(f"Failed after {self._config.retries} attempts: {e}")
                        raise
            finally:
                page.remove_listener("response", handler)

    raise RuntimeError("Request failed")  # pragma: no cover