Python Tips 5 - Webbrowser package

in STEMGeeks4 years ago (edited)

Python Tips - Webbrowser package

Python is often used as an automation tool. Today, we take a look at the webbrowser package.

Python est souvent utilisé comme outil d'automatisation. Aujourd'hui, nous nous penchons sur le paquet webbrowser.

This module is quite simple to use. That makes it very cool to work with to setup an automation script rapidly.

Ce module est très simple à utiliser. Il est donc très agréable de travailler avec lui pour mettre en place rapidement un script d'automatisation.


You can import it with:

import webbrowser

Simply open an url:

# pass the url as a string
webbrowser.open(url)

Open a url in a new tab:

# pass the url as a string
webbrowser.open_new_tab(url)

Open a url in a new window:

# pass the url as a string
webbrowser.open_new(url)

By using the package this way, you will open the URLs in your default browser. If you wish to use another browser, you will have to use the controller object.

The list of browsers supported natively can be found here.

If it's not there, you can use the webbrowser.register() function to register it before using the associated controller.


To get the controller, it's quite simple

# pass the url as a string
firefox = webbrowser.get(using="firefox")

Then you can use it just like before.

# pass the url as a string
firefox.open(url)

# pass the url as a string
firefox.open_new_tab(url)

# pass the url as a string
firefox.open_new(url)

You made it to the end, bravo! If you have any questions, don't forget to ask. See you next time!

You will be able to find a good part of the articles in this account in this repository.

To go directly to the section you are currently viewing click here.

Latest article in the series: Python Tips 4 - Playing with recursion

Sort:  

Thanks for sharing a nice tutorial.I like the way you share repository with user. We are looking for people like you in our community.

Your post has been submitted to be curated with @gitplait community account because this is the kind of publications we like to see in our community.

Join our Community on Hive

Thanks to @theophile.roos for burning 800 PLANET! You have been rewarded with a 80% vote. Your action makes this project grow and helps to restore a Clean Planet! Join us on our Discord Channel and on our website

I use this after generating HTML reports, then opens it to the default browser. One thing I observed was when the local filepath is incorrect, it would open Microsoft Edge instead 🤔

Linux is always the solving element