Skip to main content
Welcome back. In this lesson we’ll build a compact, practical AI browser agent using Python and Playwright. This example shows how to programmatically render a page, capture a screenshot, extract on-page text, and summarize it with GPT-4. Before you begin, review the Playwright documentation for installation details, browser support, device descriptors, and advanced selectors.
This image shows a webpage from the Playwright documentation, specifically the installation page, with sections on how to install Playwright and related learning topics.
Install Playwright and its browser binaries once per environment. In Jupyter notebooks, prefix shell commands with !.

Installation and imports

Run these commands in a Jupyter notebook cell to install Playwright, its browser binaries, and python-dotenv:
Quick reference — common setup commands: Now import the modules you will use and load environment variables:
Keep your OpenAI API key in an environment variable (for example, OPENAI_API_KEY). Set the key for the openai library as shown below.
Never commit API keys to source control. Use environment variables or a secrets manager, and avoid printing your key in logs.

The browsing-and-summarizing function

Below is a complete asynchronous function you can place in a single Jupyter cell. It:
  • launches a headless Chromium browser with Playwright,
  • sets a custom user-agent and viewport,
  • navigates to a URL and waits for DOMContentLoaded,
  • captures and displays a full-page screenshot in the notebook,
  • scrapes the first three paragraph elements from the Wikipedia content block (#mw-content-text p),
  • sends the scraped text to GPT-4 for summarization,
  • prints the extracted snippet and the GPT-4 summary.
Place the whole function in one cell and run it.

Example: user agent, viewport, and running the agent

Create a user-agent string that simulates an iPhone-like browser and a viewport dictionary that mimics an iPhone 12 resolution. Then run the asynchronous function with asyncio.run.
When executed, the notebook will show the rendered page screenshot (using the supplied user agent and viewport), print the first portion of the scraped Wikipedia text, and print the GPT-4–generated summary. From this base you can extend the agent to:
  • scrape and aggregate content from multiple pages,
  • index or store extracted highlights,
  • generate study aids, flashcards, or quizzes automatically,
  • add navigation logic to follow links, handle pagination, or respect robots.txt.
The image shows a Jupyter Notebook interface displaying some text about OpenAI, its AI models, and corporate structure. The content includes an extracted Wikipedia entry and a GPT-generated summary.
Thank you for reading.

Watch Video