Using a web browser in Python

Hey guys, in this tutorial we will learn about how we can open and use a web browser using Python code. This is very simple. Python provides us with a webbrowser module for this purpose to make our job very simple. Let’s see more on this topic further in this tutorial.

There are different methods defined in the webbrowser module to deal with browser and web-based documents. Some of these functions have been discussed here. Go through each method to understand the concept clearly.

webbrowser.open()

We can use open() method of webbrowser module to open a website as shown in the below code.

import webbrowser
webbrowser.open('codespeedy.com.')

The above code opens the website ‘codespeedy.com’ in the default browser.

webbrowser.open_new()

This method in Python opens a web page in a new browser window if possible. See the below code.

import webbrowser 
webbrowser.open_new('codespeedy.com.')

webbrowser.open_new_tab()

This method of webbrowser module opens the page in a new tab in the currently open window of the default browser. See the below code for a better understanding.

import webbrowser
webbrowser.open_new_tab('codespeedy.com.')

webbrowset.get()

Using webbrowser.get() method we can have control over the browser we want to open our web page. See the code given below.

import webbrowser
browser = webbrowser.get('firefox')
browser.open('codespeedy.com')
browser.open_new('codespeedy.com')

If the browser given does not exist on your system or path is not properly given, an error is raised. See below code.

import webbrowser
browser = webbrowser.get('google-chrome')
browser.open('codespeedy.com')
browser.open_new('codespeedy.com')

The above code gives error as shown below in the output:

Traceback (most recent call last):
File "web.py", line 2, in <module>
browser = webbrowser.get('google-chrome')
File "C:\Users\Ranjeet Verma\Anaconda3\lib\webbrowser.py", line 65, in get
raise Error("could not locate runnable browser")
webbrowser.Error: could not locate runnable browser

If not working, try providing the path of your browser as shown in the below program.

import webbrowser
browser = webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s')
browser.open('codespeedy.com')
browser.open_new('codespeedy.com')

We can also open a webpage using the following command in the command prompt.

python -m webbrowser -t "https://codespeedy.com"

The above command will open the given page in a new tab in the default browser of your system. To open it in a new window, replace ‘-t’ with ‘-n’. Note that for this command to run you must have python installed in your system.

Thank you.

Also read: Host your Web Application on PythonAnywhere.com

Leave a Reply

Your email address will not be published. Required fields are marked *