Python webbrowser module

Open new instance of specified web browser

nick3499
Oct 15, 2020
screen capture of Python interactive shell in terminal emulator

Import webbrowser module

In Python interactive shell, import the webbrowser module:

>>> import webbrowser as wb

The two methods we will be concerned with are get and open_new which can be listed using dir(wb):

>>> dir(wb)
['BackgroundBrowser', 'BaseBrowser', 'Chrome', 'Chromium', 'Elinks', 'Error', 'Galeon', 'GenericBrowser', 'Grail', 'Konqueror', 'Mozilla', 'Netscape', 'Opera', 'UnixBrowser', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_browsers', '_lock', '_os_preferred_browser', '_synthesize', '_tryorder', 'get', 'main', 'open', 'open_new', 'open_new_tab', 'os', 'register', 'register_X_browsers', 'register_standard_browsers', 'shlex', 'shutil', 'subprocess', 'sys', 'threading']

After confirming that get and open_new are available to the webbrowser module, an instruction can be written:

get() method

wb.get() will be passed a specific web browser name string argument, which returns a browser type controller object. In this case, we will use google-chrome for the example:

>>> wb.get('google-chrome')
<webbrowser.Chrome object at 0x7f472ef06a60>

open_new() method

The final method we will be concerned with is open_new which can be listed using dir(wb.get('google-chrome')):

>>> dir(wb.get('google-chrome'))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_invoke', 'args', 'background', 'basename', 'name', 'open', 'open_new', 'open_new_tab', 'raise_opts', 'redirect_stdout', 'remote_action', 'remote_action_newtab', 'remote_action_newwin', 'remote_args']

wb.get().open_new() will be passed a specific URL string argument, which opens a new web browser instance in Google Chrome:

>>> wb.get('google-chrome').open_new('http://www.python.org')
True

If all goes well, the Python interactive shell (aka REPL) will open a browser page and return True in the shell.

--

--

nick3499
nick3499

Written by nick3499

coder of JavaScript and Python

No responses yet