webbrowser — 方便的 Web 浏览器控制器

源代码: Lib/webbrowser.py


The webbrowser module provides a high-level interface to allow displaying web-based documents to users. Under most circumstances, simply calling the open() function from this module will do the right thing.

Under Unix, graphical browsers are preferred under X11, but text-mode browsers will be used if graphical browsers are not available or an X11 display isn’t available. If text-mode browsers are used, the calling process will block until the user exits the browser.

若环境变量 BROWSER exists, it is interpreted as the os.pathsep -separated list of browsers to try ahead of the platform defaults. When the value of a list part contains the string %s , then it is interpreted as a literal browser command line to be used with the argument URL substituted for %s ; if the part does not contain %s , it is simply interpreted as the name of the browser to launch. [ 1 ]

For non-Unix platforms, or when a remote browser is available on Unix, the controlling process will not wait for the user to finish with the browser, but allow the remote browser to maintain its own windows on the display. If remote browsers are not available on Unix, the controlling process will launch a new browser and wait.

On iOS, the BROWSER environment variable, as well as any arguments controlling autoraise, browser preference, and new tab/window creation will be ignored. Web pages will always be opened in the user’s preferred browser, in a new tab, with the browser being brought to the foreground. The use of the webbrowser module on iOS requires the ctypes module. If ctypes isn’t available, calls to open() will fail.

脚本 webbrowser can be used as a command-line interface for the module. It accepts a URL as the argument. It accepts the following optional parameters:

  • -n / --new-window opens the URL in a new browser window, if possible.

  • -t / --new-tab opens the URL in a new browser page (“tab”).

The options are, naturally, mutually exclusive. Usage example:

python -m webbrowser -t "https://www.python.org"