Introduction
The webbrowser module in Python provides a simple interface to open web browsers, display HTML documents, and navigate the web. This practical lab will walk you through the basics of using the webbrowser package, from opening a URL in a new tab to executing a Google search directly from the Python console.
Opening a URL in a new tab
The webbrowser module makes it easy to open a URL in a new browser tab. Let's start by importing the webbrowser module and calling the open_new_tab() function to open a URL:
Open the Python Shell
Open the Python shell by typing the following command in the terminal.
python3
Import the web browser module and use the open_new_tab() function to open the URL.
import webbrowser
url = "https://www.google.com"
webbrowser.open_new_tab(url)
When you run this code, a new browser tab should open and navigate to Google's homepage.
The open() Function
If you want to open a URL in the user's default browser, you can use the open() function instead of open_new_tab():
webbrowser.open(url)
Use the open_new_tab() open the HTML file in a new browser tab
The webbrowser module can also be used to display HTML files. A simple HTML file named "example.html" is provided here.
We can use the open_new_tab() function to display this HTML file in a new browser tab:
file_path = "/home/labex/project/example.html"
webbrowser.open_new_tab(file_path)
When you run this code, a new browser tab should open and display the contents of example.html.
Create and use the google_search() Function
The webbrowser module can even be used to execute a Google search directly from the Python console. Let's create a function that takes a search query as an argument and uses the webbrowser module to execute a Google search:
def google_search(query):
url = "https://www.google.com/search?q=" + query
webbrowser.open_new_tab(url)
Now we can call the google_search() function with a search query:
google_search("python web scraping")
When you run this code, a new browser tab should open and display the Google search results for "python web scraping".
Summary
In this lab, you learned the basics of using Python's webbrowser package to interact with the web. You learned how to open a URL in a new browser tab, display local HTML files, and even execute a Google search directly from the Python console. The webbrowser module is a powerful tool for automating web-based tasks and integrating Python scripts with the web.



