Skip to content

BrowserContext

conatus.utils.browser.context

Browser context module.

A browser context is a container for a set of pages. A FullBrowser can have one or multiple contexts. Think of a context as a container for cookies, etc. that are shared across multiple pages. A browser can have an incognito context in addition to a normal context, for example.

This module is used in conjunction with the Page module. Each context can have one or multiple pages.

Configuration

You can configure some parameters for the context:

  • Screen size: Settings related to the screen size.

    • initial_viewport: The initial size of the viewport. (The viewport size can change during the browsing session, I believe.) Default is (1100, 700).
    • device_scale_factor: The device scale factor. Default is 1.0.
  • Device settings: Settings related to the device.

    • device_type: The device type. Default is Desktop Chrome HiDPI.

Note

You have to pass a full BrowserConfig instance during instantiation of the context, not just the context configuration.

Viewport

Bases: BaseModel

Viewport size.

Similar to playwright._impl._api_structures.ViewportSize.

width class-attribute instance-attribute

width: int = Field(gt=200)

The width, in pixels. Need to be greater than 200.

height class-attribute instance-attribute

height: int = Field(gt=200)

The height, in pixels. Need to be greater than 200.

DeviceConfig

DeviceConfig(**data: str | Viewport | float | bool)

Bases: BaseModel

Device configuration.

Acts as a wrapper around what Playwright calls a device.

More information can be found in the Playwright documentation: https://playwright.dev/python/docs/api/class-playwright#playwright-devices

Source code in conatus/utils/browser/context.py
def __init__(self, **data: str | Viewport | float | bool) -> None:
    """Initialize the device configuration."""
    if "viewport" not in data:
        data["viewport"] = DEFAULT_VIEWPORT_OBJ
    if "device_scale_factor" not in data:
        data["device_scale_factor"] = DEFAULT_SCALE_F
    if "is_mobile" not in data:
        data["is_mobile"] = False
    if "has_touch" not in data:
        data["has_touch"] = False
    if "default_browser_type" not in data:
        data["default_browser_type"] = "chrome"
    if "user_agent" not in data:
        data["user_agent"] = DEFAULT_USER_AGENT
    super().__init__(**data)

user_agent instance-attribute

user_agent: str

The user agent.

viewport instance-attribute

viewport: Viewport

The viewport size. Defaults to (1100, 700).

device_scale_factor instance-attribute

device_scale_factor: float

The device scale factor. Defaults to 1.0.

is_mobile instance-attribute

is_mobile: bool

Whether the device is mobile.

has_touch instance-attribute

has_touch: bool

Whether the device has touch.

default_browser_type instance-attribute

default_browser_type: str

The default browser type.

BrowserContext

BrowserContext(
    pw: Playwright,
    browser_instance: Browser,
    config: BrowserConfig,
    *,
    async_init: bool = False
)

Browser context module.

Init in sync or async context

You can initialize the browser context in a sync or async context:

from conatus.utils.browser.context import BrowserContext
from conatus.utils.browser.full import FullBrowser

browser = FullBrowser(headless=True)
pw, browser_instance, cfg = browser.pw, browser.instance, browser.config

# Sync context
context = BrowserContext(pw, browser_instance, cfg)

# Async context
# context = await BrowserContext.init_async(pw, browser_instance, cfg)
PARAMETER DESCRIPTION
pw

The Playwright instance.

TYPE: Playwright

browser_instance

The Playwright browser instance.

TYPE: Browser

config

The browser configuration.

TYPE: BrowserConfig

async_init

Whether this function is called in an async context. Users should not set this parameter. Defaults to False.

TYPE: bool DEFAULT: False

Source code in conatus/utils/browser/context.py
def __init__(
    self,
    pw: Playwright,
    browser_instance: PlaywrightBrowser,
    config: BrowserConfig,
    *,
    async_init: bool = False,
) -> None:
    """Initialize the browser context.

    # Init in sync or async context

    You can initialize the browser context in a sync or async context:

    ```python
    from conatus.utils.browser.context import BrowserContext
    from conatus.utils.browser.full import FullBrowser

    browser = FullBrowser(headless=True)
    pw, browser_instance, cfg = browser.pw, browser.instance, browser.config

    # Sync context
    context = BrowserContext(pw, browser_instance, cfg)

    # Async context
    # context = await BrowserContext.init_async(pw, browser_instance, cfg)
    ```

    Args:
        pw: The Playwright instance.
        browser_instance: The Playwright browser instance.
        config: The browser configuration.
        async_init: Whether this function is called in an async context.
            Users should not set this parameter. Defaults to False.
    """
    initial_viewport = config.context.initial_viewport
    device_scale_f = config.context.device_scale_factor
    device_type = config.context.device_type
    self.device = self._set_device(
        pw,
        initial_viewport=initial_viewport,
        device_scale_factor=device_scale_f,
        device_type=device_type,
    )
    self.config = config
    if async_init is False:
        run_async(
            self._finish_init(browser_instance, config),
            loop=pw._loop,  # noqa: SLF001 # pyright: ignore[reportPrivateUsage, reportAny]
        )

bc instance-attribute

bc: BrowserContext

The Playwright browser context.

pages instance-attribute

pages: list[Page]

The pages in the context.

device instance-attribute

device: DeviceConfig = _set_device(
    pw,
    initial_viewport=initial_viewport,
    device_scale_factor=device_scale_f,
    device_type=device_type,
)

The device configuration.

config instance-attribute

config: BrowserConfig = config

The browser configuration.

init_async async classmethod

init_async(
    pw: Playwright,
    browser_instance: Browser,
    config: BrowserConfig,
) -> BrowserContext

Create a BrowserContext instance in an async context.

PARAMETER DESCRIPTION
pw

The Playwright instance.

TYPE: Playwright

browser_instance

The Playwright browser instance.

TYPE: Browser

config

The browser configuration.

TYPE: BrowserConfig

RETURNS DESCRIPTION
BrowserContext

The browser context.

TYPE: BrowserContext

Source code in conatus/utils/browser/context.py
@classmethod
async def init_async(
    cls,
    pw: Playwright,
    browser_instance: PlaywrightBrowser,
    config: BrowserConfig,
) -> "BrowserContext":
    """Create a BrowserContext instance in an async context.

    Args:
        pw: The Playwright instance.
        browser_instance: The Playwright browser instance.
        config: The browser configuration.

    Returns:
        BrowserContext: The browser context.
    """
    instance = cls(
        pw=pw,
        browser_instance=browser_instance,
        config=config,
        async_init=True,
    )
    await instance._finish_init(browser_instance, config)
    return instance

new_page_async async

new_page_async() -> None

Create a new page in an async context.

Source code in conatus/utils/browser/context.py
async def new_page_async(self) -> None:
    """Create a new page in an async context."""
    page = await Page.init_async(self.bc, self.config)
    self.pages.append(page)

new_page

new_page() -> None

Create a new page.

Source code in conatus/utils/browser/context.py
def new_page(self) -> None:
    """Create a new page."""
    run_async(self.new_page_async(), loop=self.bc._loop)  # noqa: SLF001 # pyright: ignore[reportPrivateUsage, reportAny]

close_async async

close_async() -> None

Close the browser context in an async context.

Source code in conatus/utils/browser/context.py
async def close_async(self) -> None:
    """Close the browser context in an async context."""
    await self.bc.close()

close

close() -> None

Close the browser context.

Warning

Please try to ensure that, if you use this method, you also remove the page from the context's list of pages.

from conatus.utils.browser.full import FullBrowser

browser = FullBrowser()
bad_context = browser.contexts[0]
bad_context.close()
browser.contexts.pop(0)
Source code in conatus/utils/browser/context.py
def close(self) -> None:
    """Close the browser context.

    !!! warning
        Please try to ensure that, if you use this method, you also
        remove the page from the context's list of pages.

    ```python
    from conatus.utils.browser.full import FullBrowser

    browser = FullBrowser()
    bad_context = browser.contexts[0]
    bad_context.close()
    browser.contexts.pop(0)
    ```
    """
    run_async(self.close_async(), loop=self.bc._loop)  # noqa: SLF001 # pyright: ignore[reportPrivateUsage, reportAny]