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.