Skip to content

Some suggestions on code hints #4

@yie1d

Description

@yie1d

Since I’m working on a similar project myself, I personally find it annoying to have to jump to the corresponding file or documentation before and after executing a CDP command just to see the exact API results. It would be great if, when using the event return, the system could immediately show what fields the event actually contains.

import asyncio
from typing import Optional

from cdp_use.cdp.target.events import AttachedToTargetEvent
from cdp_use.client import CDPClient


def on_attached_to_target(
    event: AttachedToTargetEvent, session_id: Optional[str]
) -> None:
    print(
        f"Attached to target: {event['targetInfo']['title']}, session_id: {session_id}"
    )
    

async def main():
    async with CDPClient("ws://127.0.0.1:9222/devtools/browser/...") as client:
        client.register.Target.attachedToTarget(on_attached_to_target)

        targets = await client.send.Target.getTargets()
        print(targets)

        target_id = targets["targetInfos"][0]["targetId"]
        attach_to_target_response = await client.send.Target.attachToTarget(
            params={"targetId": target_id, "flatten": True}
        )

        session_id = attach_to_target_response["sessionId"]

        if session_id is None:
            raise ValueError("Session ID is None")

        # Navigate and receive events
        await client.send.Page.navigate(
            {"url": "https://example.com"}, session_id=session_id
        )
        await asyncio.sleep(20)  # Keep listening for events


if __name__ == "__main__":
    asyncio.run(main())

The desired effect would be similar to

import asyncio

from cdpkit.connection import CDPSessionManager
from cdpkit.protocol import Page, Target


async def main():
    session_manager = CDPSessionManager(ws_endpoint='localhost:9222')
    client = await session_manager.get_session()

    targets = await client.execute(Target.GetTargets())
    print(targets)

    target_id = targets.targetInfos[0].targetId

    resp = await client.execute(Target.AttachToTarget(target_id=target_id))

    session_id = resp.sessionId

    if session_id is None:
        raise ValueError("Session ID is None")

    await client.execute(Page.Navigate(url='https://example.com'))
    await asyncio.sleep(20)


asyncio.run(main())

You can type a . to have the dev tools show you the exact parameter options.

For more details, please refer to cdpkit

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions