Claude Code for webbrowser: Python Browser Launch and URL Opening — Claude Skills 360 Blog
Blog / AI / Claude Code for webbrowser: Python Browser Launch and URL Opening
AI

Claude Code for webbrowser: Python Browser Launch and URL Opening

Published: December 1, 2028
Read time: 5 min read
By: Claude Skills 360

Python’s webbrowser module opens URLs in the system’s default browser and supports registering custom browser controllers. import webbrowser. Open in default browser: webbrowser.open(url, new=0, autoraise=True)new=0 same window/tab, new=1 new window (open_new), new=2 new tab (open_new_tab); returns True on success. Convenience: webbrowser.open_new(url) → new window; webbrowser.open_new_tab(url) → new tab. Get a controller: b = webbrowser.get(using=None) — returns the default browser controller, or a named one (e.g. "firefox", "chrome", "safari", "lynx"); raises Error if the named browser is not found. Register: webbrowser.register(name, constructor, instance=None, preferred=False) — adds a custom browser; if preferred=True it can become the default when BROWSER env var matches. Environment: BROWSER env var overrides the browser selection (e.g. BROWSER=firefox). Built-in controllers: BackgroundBrowser, GenericBrowser, Konqueror, Elinks, Mozilla, Netscape, Galeon, Opera, Epiphany, Chrome, Chromium, MacOSX, Edge, Ie. File URLs: use pathlib.Path(p).as_uri()"file:///..." to open local HTML files. Claude Code generates help-link launchers, documentation openers, OAuth callback helpers, file-to-browser viewers, and local HTML preview servers.

CLAUDE.md for webbrowser

## webbrowser Stack
- Stdlib: import webbrowser
- Open:   webbrowser.open(url)                # default browser, same window
-         webbrowser.open_new(url)            # new window
-         webbrowser.open_new_tab(url)        # new tab
- Get:    b = webbrowser.get("firefox")       # named browser
-         b.open(url)
- File:   webbrowser.open(Path(f).as_uri())   # local HTML
- Note:   BROWSER env var overrides selection

webbrowser Browser Launch Pipeline

# app/webbrowserutil.py — open helpers, file preview, OAuth, doc launcher
from __future__ import annotations

import os
import sys
import time
import urllib.parse
import webbrowser
from dataclasses import dataclass
from pathlib import Path


# ─────────────────────────────────────────────────────────────────────────────
# 1. Safe open helpers
# ─────────────────────────────────────────────────────────────────────────────

def open_url(
    url: str,
    new: int = 2,
    delay: float = 0.0,
) -> bool:
    """
    Open a URL in the default browser (new=2 → new tab by default).
    Returns True if the browser was launched, False on failure.
    Optional delay in seconds before opening (useful in server startups).

    Example:
        open_url("https://example.com")
        open_url("https://docs.example.com", new=1)   # new window
    """
    if delay > 0:
        time.sleep(delay)
    try:
        return webbrowser.open(url, new=new, autoraise=True)
    except Exception:
        return False


def open_file(path: "str | Path", new: int = 2) -> bool:
    """
    Open a local file (HTML, PDF, etc.) in the default browser.
    Converts the path to a file:// URI automatically.

    Example:
        open_file("/tmp/report.html")
        open_file(Path("dist/index.html"))
    """
    uri = Path(path).resolve().as_uri()
    return open_url(uri, new=new)


def open_with_browser(browser_name: str, url: str, new: int = 2) -> bool:
    """
    Open url with a specific named browser.
    Falls back to the default browser if the named one is not found.

    Example:
        open_with_browser("firefox", "https://example.com")
        open_with_browser("chrome", "https://canary.example.com")
    """
    try:
        b = webbrowser.get(browser_name)
        return b.open(url, new=new, autoraise=True)
    except webbrowser.Error:
        return webbrowser.open(url, new=new, autoraise=True)


# ─────────────────────────────────────────────────────────────────────────────
# 2. URL builder helpers
# ─────────────────────────────────────────────────────────────────────────────

def build_url(base: str, **params: str) -> str:
    """
    Append query parameters to a base URL.

    Example:
        url = build_url("https://search.example.com", q="python tempfile", page="1")
        open_url(url)
    """
    if not params:
        return base
    return base + "?" + urllib.parse.urlencode(params)


def search_url(
    query: str,
    engine: str = "google",
) -> str:
    """
    Build a search URL for a common search engine.

    Example:
        open_url(search_url("python webbrowser module"))
        open_url(search_url("tempfile docs", engine="duckduckgo"))
    """
    q = urllib.parse.quote_plus(query)
    engines = {
        "google":     f"https://www.google.com/search?q={q}",
        "duckduckgo": f"https://duckduckgo.com/?q={q}",
        "bing":       f"https://www.bing.com/search?q={q}",
        "github":     f"https://github.com/search?q={q}",
        "pypi":       f"https://pypi.org/search/?q={q}",
        "docs":       f"https://docs.python.org/3/search.html?q={q}",
    }
    return engines.get(engine, engines["google"])


# ─────────────────────────────────────────────────────────────────────────────
# 3. OAuth / local callback helper
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class OAuthBrowserFlow:
    """
    Helper for browser-based OAuth flows: open the auth URL, then wait for
    the user to complete the flow (the callback is handled externally).

    Example:
        flow = OAuthBrowserFlow(
            auth_url="https://auth.example.com/oauth/authorize",
            client_id="my-client-id",
            redirect_uri="http://localhost:8080/callback",
            scope="read write",
        )
        flow.open()
        # ... start a local HTTP server to catch the callback ...
    """
    auth_url:      str
    client_id:     str
    redirect_uri:  str
    scope:         str = ""
    response_type: str = "code"
    state:         str = ""

    def build_auth_url(self) -> str:
        """Construct the full authorization URL with query parameters."""
        params: dict[str, str] = {
            "client_id":     self.client_id,
            "redirect_uri":  self.redirect_uri,
            "response_type": self.response_type,
        }
        if self.scope:
            params["scope"] = self.scope
        if self.state:
            params["state"] = self.state
        return build_url(self.auth_url, **params)

    def open(self, delay: float = 0.5) -> bool:
        """
        Open the authorization URL in a new browser tab.

        Example:
            flow.open(delay=1.0)   # give your local server time to start
        """
        url = self.build_auth_url()
        return open_url(url, new=2, delay=delay)


# ─────────────────────────────────────────────────────────────────────────────
# 4. Documentation launcher
# ─────────────────────────────────────────────────────────────────────────────

_STDLIB_DOC_BASE = "https://docs.python.org/3/library/"

def open_stdlib_docs(module: str) -> bool:
    """
    Open the official Python docs page for a stdlib module.

    Example:
        open_stdlib_docs("pathlib")
        open_stdlib_docs("asyncio")
    """
    slug = module.replace(".", "-").lower()
    url = f"{_STDLIB_DOC_BASE}{slug}.html"
    return open_url(url)


def open_pypi(package: str) -> bool:
    """
    Open the PyPI page for a package.

    Example:
        open_pypi("requests")
    """
    return open_url(f"https://pypi.org/project/{urllib.parse.quote(package)}/")


@dataclass
class DocLauncher:
    """
    Map symbolic names to documentation URLs and open them on demand.

    Example:
        docs = DocLauncher({
            "api":  "https://api.example.com/docs",
            "wiki": "https://wiki.example.com/Home",
        })
        docs.open("api")
    """
    links: dict[str, str]

    def open(self, name: str, new: int = 2) -> bool:
        """Open the URL registered under name. Returns False if name unknown."""
        url = self.links.get(name)
        if url is None:
            print(f"[webbrowser] unknown doc '{name}'. "
                  f"Available: {', '.join(self.links)}", file=sys.stderr)
            return False
        return open_url(url, new=new)

    def list(self) -> list[str]:
        return list(self.links)


# ─────────────────────────────────────────────────────────────────────────────
# 5. HTML preview (write temp HTML and open it)
# ─────────────────────────────────────────────────────────────────────────────

def preview_html(html: str, title: str = "Preview") -> Path:
    """
    Write html to a NamedTemporaryFile and open it in the browser.
    Returns the temp file path (caller responsible for deletion if desired).

    Example:
        preview_html("<h1>Hello</h1><p>world</p>")
    """
    import tempfile
    with tempfile.NamedTemporaryFile(
        mode="w", suffix=".html", delete=False, encoding="utf-8"
    ) as f:
        if not html.lstrip().startswith("<!"):
            html = (
                f"<!DOCTYPE html><html><head>"
                f"<meta charset='utf-8'><title>{title}</title>"
                f"</head><body>{html}</body></html>"
            )
        f.write(html)
        p = Path(f.name)
    open_file(p)
    return p


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    print("=== webbrowser demo ===")

    # ── list available browsers ───────────────────────────────────────────────
    print("\n--- webbrowser info ---")
    try:
        default = webbrowser.get()
        print(f"  default controller: {default.__class__.__name__}")
    except webbrowser.Error as e:
        print(f"  no default browser: {e}")

    env_browser = os.environ.get("BROWSER", "(not set)")
    print(f"  BROWSER env: {env_browser}")

    # ── build_url ─────────────────────────────────────────────────────────────
    print("\n--- build_url ---")
    url = build_url("https://example.com/search", q="python webbrowser", page="1")
    print(f"  {url}")

    # ── search_url ────────────────────────────────────────────────────────────
    print("\n--- search_url ---")
    for engine in ["google", "duckduckgo", "pypi", "docs"]:
        print(f"  {engine}: {search_url('python webbrowser', engine=engine)[:60]}...")

    # ── OAuthBrowserFlow.build_auth_url ───────────────────────────────────────
    print("\n--- OAuthBrowserFlow ---")
    flow = OAuthBrowserFlow(
        auth_url="https://auth.example.com/oauth/authorize",
        client_id="abc123",
        redirect_uri="http://localhost:8080/callback",
        scope="read write",
        state="xyz789",
    )
    print(f"  auth url: {flow.build_auth_url()[:80]}...")

    # ── stdlib docs URL ───────────────────────────────────────────────────────
    print("\n--- stdlib doc URLs ---")
    for mod in ["pathlib", "asyncio", "http.cookiejar"]:
        slug = mod.replace(".", "-")
        print(f"  {mod}: {_STDLIB_DOC_BASE}{slug}.html")

    # ── DocLauncher ───────────────────────────────────────────────────────────
    print("\n--- DocLauncher ---")
    launcher = DocLauncher({
        "api":  "https://api.example.com/docs",
        "wiki": "https://wiki.example.com/",
    })
    print(f"  available: {launcher.list()}")
    print(f"  open 'unknown': {launcher.open('unknown')}")

    # ── open_file URI ─────────────────────────────────────────────────────────
    print("\n--- file URI ---")
    p = Path("/tmp/demo_preview.html")
    print(f"  as_uri: {p.as_uri()}")

    print("\n  (browser open calls skipped in demo — use interactively)")
    print("\n=== done ===")

For the subprocess alternative — subprocess.Popen(["xdg-open", url]) on Linux or subprocess.Popen(["open", url]) on macOS launches a browser directly without going through webbrowser’s controller registry — use webbrowser for portable cross-platform browser launching since it handles Windows (start), macOS (open), and Linux (xdg-open, gnome-open) automatically; use subprocess when you need to specify exact arguments (headless mode, profile, window size) that webbrowser’s API does not expose, or when launching non-browser applications. For the playwright / selenium alternative — headless browser automation that controls Chrome or Firefox programmatically from Python — use webbrowser for simple URL opening in the user’s browser without any programmatic feedback; use playwright or selenium when you need to interact with the page (click links, fill forms, wait for JavaScript, scrape content, take screenshots). The Claude Skills 360 bundle includes webbrowser skill sets covering open_url()/open_file()/open_with_browser() safe open helpers, build_url()/search_url() URL builders, OAuthBrowserFlow with build_auth_url()/open() for browser-based OAuth, DocLauncher symbolic documentation link registry, and preview_html() write-and-open HTML preview. Start with the free tier to try browser launch patterns and webbrowser pipeline code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free