Open Web Browser Window or New Tab With Python

 ·  · 

Python webbrowser module provided convenient API to control web browser.


1 Command Line

Python webbrowser module can be used directly in command line.

$ python3 -m webbrowser -t ""

Executing above command will open the URL in a new page tab of system default web browser.

Alternatively, using -n option will open the URL in a new web browser window.



2.1 Default Browser

Open URL with system default web browser.

#!/usr/bin/env python3

import webbrowser

a_website = ""

# Open url in a new window of the default browser, if possible

# Open url in a new page (“tab”) of the default browser, if possible
webbrowser.open_new_tab(a_website), 1) # Equivalent to: webbrowser.open_new(a_website), 2) # Equivalent to: webbrowser.open_new_tab(a_website)

2.2 Specify A Browser Type

Furthermore, you can select an optional browser to open the url.

#!/usr/bin/env python3

import webbrowser

a_website = ""


webbrowser.get will return a controller object for the browser type you passed. All available and registered web browser types can be inspected by webbrowser._browsers.

>>> import webbrowser
>>> webbrowser._browsers
>>> {'macosx': [None, <webbrowser.MacOSXOSAScript object at 0x10f6e7668>], 'safari': [None, <webbrowser.MacOSXOSAScript object at 0x10f6ab4a8>], 'firefox': [None, <webbrowser.MacOSXOSAScript object at 0x10f6ab978>]}

If not pass browser type or pass None (default value) to webbrowser.get, it will return a controller object for a browser type according to the webbrowser._tryorder.

If your webbrowser._tryorder are as follows, webbrowser.get() or webbrowser.get(None) will return a controller object for a browser type 'MacOSX'.

>>> webbrowser._tryorder
>>> ['MacOSX', 'firefox', 'safari']

2.3 Register A Browser Type

If you want to use a browser that is not in webbrowser._browsers list, you should register that browser type first.

#!/usr/bin/env python3

import webbrowser

a_website = ""

# last param is: update_tryorder
# update_tryorder > 0 means: append the new registered browser type into _tryorder
# update_tryorder < 0 means: insert before first element of _tryorder instead of appending
webbrowser.register('mychrome', None, webbrowser.MacOSXOSAScript('Google Chrome'), -1)


Alternatively, you can pass browser path to webbrowser.get directly. In this way webbrowser.get will register the browser type behind the scenes.

#!/usr/bin/env python3

import webbrowser

a_website = ""

# Linux
# chrome_cmd = "/usr/bin/google-chrome %s"

# Windows
# chrome_cmd = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s"

# Mac
chrome_cmd = "open -a /Applications/Google\ %s"