Automate Boring Tasks With the Python Webbrowser Module
The webbrowser module provides convenient interfaces for launching web browsers and opening web documents.
A simple example for use in .py files:
import webbrowser webbrowser.open("https://nataliiabondarenko.blogspot.com")
You can use the webbrowser as a command-line interface in the terminal:
$ python -m webbrowser "https://nataliiabondarenko.blogspot.com"
"python -m
" means we are running the webbrowser.py
library module as a script.
Open Multiple URLs
We can open multiple necessary links in the browser at the same time using a loop. These links can be a list of sites that you use every day for work.
#!/usr/bin/env python3 """ Customization: You can convert this script to a command line interface and add additional functionality. """ import webbrowser import time # what's new links = [ 'https://mail.google.com', 'https://github.com', 'https://www.linkedin.com' ] for i in links: webbrowser.open_new_tab(i) # give time to load the page time.sleep(5)
The specified URLs open in the default browser. However, this module has functions that allow you to select a browser from the browsers installed on your operating system. For a list of supported browser types and system restrictions, see the documentation for the module.
Warning! Be careful if you open many pages in your browser from the same site using scripts. Typically, a user does not request 100 web pages in 1 minute. Keep a reasonable number of links in the list and set the time interval between requests. For example, you can use time.sleep(random.uniform(5, 10))
. Don't hit the server!
Open Local Files
The webbrowser module uses the functionality of the OS to launch a web browser and open a URL.
On some platforms, you can open local files using the functions of this module. If you are using a file path on your computer instead of a URL, you can launch the operating system program associated with that file type. Be careful with executables!
The following examples are for Windows. These examples assume that the files being opened exist on the PC.
#!/usr/bin/env python3 import webbrowser import os # folder in File Explorer home_dir = os.path.expanduser('~') # html file in browser html = os.path.expanduser(r'~\Desktop\test.html') # txt file in Notepad txt = os.path.expanduser(r'~\Desktop\test.txt') # png/jpg file in Windows Photo Viewer or Photos png = os.path.expanduser(r'~\Desktop\test.png') if __name__ == '__main__': webbrowser.open(home_dir) # webbrowser.open(html) # webbrowser.open(txt) # webbrowser.open(png)
Exception Handling (joke)
This is an old joke. I saw one version of this code on Twitter, and it was written in JavaScript. The JavaScript code consisted of a try-except block and a Stack Overflow search query. I rewrote this in Python with some additions. If an error occurs while executing a function, the webbrowser opens the search results pages.
#!/usr/bin/env python3 """ https://docs.python.org/3/library/functools.html#functools.wraps @exceptions_decorator can be used with different functions """ import webbrowser import time import traceback from functools import wraps def exceptions_decorator(func): """A decorator for testing your functions.""" @wraps(func) def wrapper(*args, **kwargs): try: # your code runs here return func(*args, **kwargs) except Exception as e: error = e.__class__.__name__ stack = f'https://stackoverflow.com/search?q=python+{error}+{e}' google = f'https://google.com/search?q=python+{error}+{e}' docs = f'https://docs.python.org/3/search.html?q={error}' for i in [stack, google, docs]: webbrowser.open_new_tab(i) time.sleep(5) print(traceback.format_exc()) return wrapper @exceptions_decorator def do_it(a, b): return a / b if __name__ == '__main__': do_it(1, 0)