Tuesday Tooling - Python Webbrowser

This week a handy Python library that enables us to open a web browser!

So what is it?

Webbrowser is a Pythonic way to open a web browser on any operating system.

Can't I just use subprocess / popen / something else?

Sure you can, but using webbrowser we have a Pythonic way of calling the browser, rather than using Python to call bash / command line to run a command to open a browser there.

For arguments sake, here is how to open the default web browser on my Linux system using subprocess.

import subprocess
subprocess.call(["xdg-open","http://bigl.es"])

and here is the same thing using webbrowser

import webbrowser
webbrowser.open_new_tab("http://bigl.es")

Both are two lines of Python, but using subprocess we need to create a list that contains the command xdg-open at index 0 and then the parameters / argument that is the website is passed as a second item in the list. Not as clean and easy as webbrowser which enables us to pass the website as an argument.

So how can I install it?

It is already installed as standard!

So how can I use it?

Lets write something in IDLE3 that will open many websites in separate tabs.

The websites are saved as a list, and then we use a for loop to iterate of the items in the list and use them as the URL that we wish to open.

import webbrowser

websites = ["http://bigl.es","http://news.bbc.co.uk","http://raspberrypi.org"]

for website in websites:
    webbrowser.open_new_tab(website)

Why should you use it?

This library could be really handy for those that create custom user interfaces for those with special needs. Instead of moving a mouse to open a web page to check the news / weather / bitcoin price, we can simply use webbrowser to open the page when a button is pressed. For example here is a quick demo code that opens BBC news when a button is pressed.

from gpiozero import Button
from signal import pause
import webbrowser

def news():
    webbrowser.open_new_tab("http://news.bbc.co.uk")

button = Button(17)

button.when_pressed = news

pause()

If your intention is purely evil, then you could also use this library to open a really annoying web page based on the time of day. Obviously I am not going to give you the code for that, if you want to do that then you will have to work it out for yourself! :)

Go and have fun with it!

Give it a try, see what you can do with it!