webbrowser — Displays web pages¶
|Purpose:||Use the webbrowser module to display web pages to your users.|
webbrowser module includes functions to open URLs in interactive
browser applications. The module includes a registry of available
browsers, in case multiple options are available on the system. It can
also be controlled with the
BROWSER environment variable.
To open a page in the browser, use the
import webbrowser webbrowser.open( 'https://docs.python.org/3/library/webbrowser.html' )
The URL is opened in a browser window, and that window is raised to the top of the window stack. The documentation says that an existing window will be reused, if possible, but the actual behavior may depend on your browser’s settings. Using Firefox on Mac OS X, a new window was always created.
Windows vs. Tabs¶
If you always want a new window used, use
import webbrowser webbrowser.open_new( 'https://docs.python.org/3/library/webbrowser.html' )
If you would rather create a new tab, use
Using a specific browser¶
If for some reason your application needs to use a specific browser,
you can access the set of registered browser controllers using the
get() function. The browser controller has methods to
example forces the use of the lynx browser:
import webbrowser b = webbrowser.get('lynx') b.open('https://docs.python.org/3/library/webbrowser.html')
Refer to the module documentation for a list of available browser types.
Users can control the module from outside your application by setting
the environment variable
BROWSER to the browser names or commands
to try. The value should consist of a series of browser names
os.pathsep. If the name includes
%s, the name is
interpreted as a literal command and executed directly with the
replaced by the URL. Otherwise, the name is passed to
obtain a controller object from the registry.
For example, this command opens the web page in lynx, assuming it is available, no matter what other browsers are registered.
$ BROWSER=lynx python3 webbrowser_open.py
If none of the names in
webbrowser falls back
to its default behavior.
Command Line Interface¶
All of the features of the
webbrowser module are available via
the command line as well as from within your Python program.
$ python3 -m webbrowser Usage: .../lib/python3.7/webbrowser.py [-n | -t] url -n: open new window -t: open new tab