webbrowser

The Python webbrowser module provides a high-level interface to allow displaying web-based documents to users. It provides a quick way to open a web page in the default web browser and can also somewhat control browser behavior.

Here’s a quick example:

Python
>>> import webbrowser

>>> webbrowser.open("https://realpython.com")
True

Key Features

  • Opens URLs in the default web browser
  • Supports specifying and controlling different browsers
  • Allows opening URLs in new browser windows or tabs
  • Provides cross-platform compatibility—Windows, macOS, and Linux
  • Allows customization of browser command-line arguments
  • Handles browser launching and process management
  • Integrates easily with other Python modules and workflows

Frequently Used Classes and Functions

Object Type Description
webbrowser.open() Function Opens a URL in the default web browser
webbrowser.get() Function Returns a controller object for a browser
webbrowser.open_new() Function Opens a URL in a new browser window
webbrowser.open_new_tab() Function Opens a URL in a new tab
webbrowser.Browser Class Represents a browser controller that launches a web browser process

Examples

Open a URL in a new browser window:

Python
>>> import webbrowser

>>> webbrowser.open_new("https://www.python.org")
True

Open a URL in a new browser tab:

Python
>>> webbrowser.open_new_tab("https://www.python.org")
True

Common Use Cases

  • Opening web pages from Python code
  • Automating web browsing tasks
  • Testing web applications by automatically opening them in different browsers
  • Opening documentation, help pages, or reports for users
  • Launching web-based dashboards or GUIs from scripts
  • Implementing open-in-browser features in desktop apps
  • Automating error reporting or user support by opening URLs
  • Assisting in automated web testing setups

Real-World Example

Suppose you’re building a GUI app with Tkinter and want to give users a button to open the Python documentation in their browser. Here’s how you can do it:

Python
>>> import tkinter as tk
>>> import webbrowser

>>> root = tk.Tk()

>>> def open_in_browser():
...     webbrowser.open("https://docs.python.org/3/")
...

>>> tk.Button(
...     root, text="Open Python Docs", command=open_in_browser
... ).pack()

>>> root.mainloop()

In this example, clicking the Open Python Docs button launches the official Python documentation home page in the user’s default web browser.