Opening a web browser is a common task while working with web applications and automation. In this tutorial, we’ll see how to open a web browser in Python using the webbrowser
module.
The webbrowser
module provides a high-level interface to allow displaying of Web-based documents to the users. It comes in-built with Python, which means you don’t need to install any additional packages.
Step 1: Importing the webbrowser module
To start with, you need to import the webbrowser
module, which is a standard Python module. Simply use the import statement as shown below:
1 |
import webbrowser |
Step 2: Opening a URL in the default web browser
Next, you can open a URL in the default web browser using the webbrowser.open()
function. The webbrowser.open()
function accepts the URL as a parameter and returns True
if the operation is successful, otherwise, it returns False
. Here’s an example to demonstrate the opening of a URL:
1 2 3 4 |
import webbrowser url = "https://www.example.com" webbrowser.open(url) |
Step 3: Opening a URL in a new window or tab
You can also open a URL in a new window or a new tab of the web browser. By passing the optional new
parameter to the webbrowser.open()
function, you can control the behavior. The following table shows the meaning of different new
parameter values:
new | Meaning |
---|---|
0 | Open the URL in the same browser window if possible. |
1 | Open the URL in a new browser window, if possible. |
2 | Open the URL in a new browser tab, if possible. |
Here’s an example to demonstrate the opening of a URL in a new browser tab:
1 2 3 4 |
import webbrowser url = "https://www.example.com" webbrowser.open(url, new=2) |
Conclusion
In this tutorial, we have learned how to open a web browser in Python using the webbrowser
module. We have also seen how to open a URL in the same browser window, a new window, or a new tab. This can be useful for automating tasks that involve browsing the web or automatically opening web pages based on certain conditions.