Launching Web Pages in Real Browsers Using Python
Python provides two primary approaches for opening web pages in actual browser instances. The first method leverages the system's native capabilities via the os module, while the second uses Python’s built-in webbrowser library for more controlled interactions.
Using the os module allows launching any installed browser by specifynig its executable path directly. This approach is straightforward but limited in functionality—each call opens a single URL and does not support managing multiple tabs or windows programmatically.
import os
os.system(r'C:\Program Files\Internet Explorer\iexplore.exe http://www.baidu.com')
The webbrowser module offers greater flexibility with three main functions: open(), open_new(), and open_new_tab().
-
webbrowser.open(url, new=0, autoraise=True)opens the specified URL in the default browser. Thenewparameter detremines how the URL is displayed:new=0: Opens in the current window.new=1: Opens in a new browser window.new=2: Opans in a new tab.
-
webbrowser.open_new(url)andwebbrowser.open_new_tab(url)are convenience wrappers that internally callwebbrowser.open()with predefined values fornewandautoraise.
To target a specific browser like Chrome, you must register it explicitly:
import webbrowser
chrome_path = r'D:\Google\Chrome\Application\chrome.exe'
webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(chrome_path))
webbrowser.get('chrome').open('http://www.baidu.com', new=1, autoraise=True)
Here, 'chrome' is a custom identifier; you can use any name (e.g., chrome_custom) to reference your preferred browser.
The webbrowser module supports various browser types, including:
mozilla,firefox,netscapegaleon,epiphanyopera,graillinks,elinks,lynx,w3mwindows-default,macosx,safarigoogle-chrome,chrome,chromium,chromium-browser
Each entry maps to a corresponding class used to launch the browser. These definitions are available in the source file located at lib/webbrowser.py within the Python installation directory.