|
| 1 | +''' |
| 2 | +Monitor network events from a web page. |
| 3 | +
|
| 4 | +This example demonstrates how to listen to network events such as |
| 5 | +RequestWillBeSent, ResponseReceived, etc. It shows both patterns for |
| 6 | +handling events: |
| 7 | +
|
| 8 | +1. wait_for() - wait for a single event |
| 9 | +2. listen() - continuously listen for multiple events |
| 10 | +
|
| 11 | +To use this example, start Chrome (or any other browser that supports CDP) with |
| 12 | +the option `--remote-debugging-port=9000`. The URL that Chrome is listening on |
| 13 | +is displayed in the terminal after Chrome starts up. |
| 14 | +
|
| 15 | +Then run this script with the Chrome URL as the first argument and the target |
| 16 | +website URL as the second argument: |
| 17 | +
|
| 18 | +$ python examples/network_events.py \ |
| 19 | + ws://localhost:9000/devtools/browser/facfb2295-... \ |
| 20 | + https://www.hyperiongray.com |
| 21 | +''' |
| 22 | +import logging |
| 23 | +import os |
| 24 | +import sys |
| 25 | + |
| 26 | +import trio |
| 27 | +from trio_cdp import open_cdp, network, page, target |
| 28 | + |
| 29 | + |
| 30 | +log_level = os.environ.get('LOG_LEVEL', 'info').upper() |
| 31 | +logging.basicConfig(level=getattr(logging, log_level)) |
| 32 | +logger = logging.getLogger('network_events') |
| 33 | +logging.getLogger('trio-websocket').setLevel(logging.WARNING) |
| 34 | + |
| 35 | + |
| 36 | +async def main(): |
| 37 | + logger.info('Connecting to browser: %s', sys.argv[1]) |
| 38 | + async with open_cdp(sys.argv[1]) as conn: |
| 39 | + logger.info('Listing targets') |
| 40 | + targets = await target.get_targets() |
| 41 | + |
| 42 | + for t in targets: |
| 43 | + if (t.type == 'page' and |
| 44 | + not t.url.startswith('devtools://') and |
| 45 | + not t.attached): |
| 46 | + target_id = t.target_id |
| 47 | + break |
| 48 | + |
| 49 | + logger.info('Attaching to target id=%s', target_id) |
| 50 | + async with conn.open_session(target_id) as session: |
| 51 | + |
| 52 | + # Enable network events |
| 53 | + logger.info('Enabling network events') |
| 54 | + await network.enable() |
| 55 | + |
| 56 | + # Enable page events for navigation |
| 57 | + logger.info('Enabling page events') |
| 58 | + await page.enable() |
| 59 | + |
| 60 | + # Pattern 1: Using wait_for() to wait for a specific event |
| 61 | + # This is useful when you need to wait for a single event before |
| 62 | + # continuing execution. |
| 63 | + logger.info('Navigating to %s (using wait_for pattern)', sys.argv[2]) |
| 64 | + async with session.wait_for(page.LoadEventFired): |
| 65 | + await page.navigate(url=sys.argv[2]) |
| 66 | + logger.info('Page loaded') |
| 67 | + |
| 68 | + # Pattern 2: Using listen() to continuously monitor events |
| 69 | + # This creates an async iterator that yields events as they occur. |
| 70 | + # You can listen to multiple event types simultaneously. |
| 71 | + logger.info('Monitoring network events (press Ctrl+C to stop)...') |
| 72 | + |
| 73 | + # Create an async iterator for network events |
| 74 | + async for event in session.listen( |
| 75 | + network.RequestWillBeSent, |
| 76 | + network.ResponseReceived, |
| 77 | + network.LoadingFinished, |
| 78 | + network.LoadingFailed |
| 79 | + ): |
| 80 | + # Handle different event types |
| 81 | + if isinstance(event, network.RequestWillBeSent): |
| 82 | + logger.info( |
| 83 | + 'Request: %s %s', |
| 84 | + event.request.method, |
| 85 | + event.request.url |
| 86 | + ) |
| 87 | + elif isinstance(event, network.ResponseReceived): |
| 88 | + logger.info( |
| 89 | + 'Response: %s (status: %d)', |
| 90 | + event.response.url, |
| 91 | + event.response.status |
| 92 | + ) |
| 93 | + elif isinstance(event, network.LoadingFinished): |
| 94 | + logger.info('Loading finished: %s', event.request_id) |
| 95 | + elif isinstance(event, network.LoadingFailed): |
| 96 | + logger.info( |
| 97 | + 'Loading failed: %s (error: %s)', |
| 98 | + event.request_id, |
| 99 | + event.error_text |
| 100 | + ) |
| 101 | + |
| 102 | + |
| 103 | +if __name__ == '__main__': |
| 104 | + if len(sys.argv) != 3: |
| 105 | + sys.stderr.write('Usage: network_events.py <browser url> <target url>\n') |
| 106 | + sys.exit(1) |
| 107 | + try: |
| 108 | + trio.run(main, restrict_keyboard_interrupt_to_checkpoints=True) |
| 109 | + except KeyboardInterrupt: |
| 110 | + logger.info('Interrupted by user') |
0 commit comments