Convenient Web-browser controller in Python


To display web based documents to users by using python, there is a module called webbrowser. It provides high level interface to handle web documents.

On UNIX based system, this module supports lynx, Netscape, Mosaic etc browsers. For Windows and Macintosh, it uses the standard browsers.

To use this module, we need to import the following module.

import webbrowser

The webbrowser module has different methods, and exceptions, these are as follows −

Exception webbrowser.Error

This error will raise when there is an error in the webbrowser interface.

Method webbrowser.open(url, new=0, autoraise=True)

This method is used to display the url using default web browser. The default value of new is 0. When it is 0, it opens in the same browser, for new = 1, a new browser window will open and for new = 2, a new browser tab will open.

Method webbrowser.open_new(url)

This method is used to return a controller for the browser type using. If the value of using is None, it will return controller for the default browser.

Method webbrowser.register(name, constructor, instance=None, *, preferred=False)

This method is used to register a browser type name. After registering, we can get the browser controller using get() method. There is instance in the parameter, when the instance is not defined, the constructor will be called without any parameter.

There are some predefined browser types. Here is the list of some selected browser types. These types can be passes as get() method.

Sr.No. Type Name & Class Name
1

‘mozilla’

Mozilla(‘mozilla’)

2

‘firefox

Mozilla(‘mozilla’)

3

‘netscape’

Mozilla(‘netscape’)

4

‘opera’

Opera()

5

‘links’

GenericBrowser(‘links’)

6

‘lynx’

GenericBrowser(‘lynx’)

7

‘safari’

MacOSX(‘safari’)

8

‘windows-default’

WindowsDefault

9

‘chrome’

Chrome(‘chrome’)

10

‘chromium’

Chromium(‘chromium’)

Example Code

import webbrowser as browser
my_browser = browser.get('windows-default')
my_browser.open_new('http://www.tutorialspoint.com')

Output

Browser Controller in python

Updated on: 30-Jul-2019

708 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements