How to capture background requests and responses in Playwright?

You can capture background requests and responses in Playwright by registering appropriate callback functions for the request and response events of the Page object.

Here is some sample code that logs all requests and responses in Playwright:

from playwright.sync_api import sync_playwright

def incercept_request(request):
    print("requested URL:", request.url)

def incercept_response(response):
    print(f"response URL: {response.url}, Status: {response.status}")

with sync_playwright() as p:
    browser = p.chromium.launch(headless = False)

    page = browser.new_page()
    
    # Register the middlewares
    page.on("request", incercept_request)
    page.on("response", incercept_response)

    page.goto("https://scrapingbee.com")

Note: You can modify requests and responses via these middlewares as well!

Related Playwright web scraping questions: