如何指定X浏览器打开网页后无需关闭即可继续执行Python脚本?
Hey there, I see the issue you're running into—when you specify Chrome directly with the path including %s, the script blocks until you close the browser. Here's how to fix it, plus a breakdown of why it was happening:
Working Solution 1: Correct Path Formatting
The problem comes from how you're passing the Chrome path. When you append %s directly to the executable path, Python treats the entire string as the program to run, which forces a blocking execution. Instead, wrap the path in quotes and separate the %s parameter properly:
import webbrowser # Define the Chrome executable path (no %s here) chrome_exe = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe' # Create the browser instance with proper parameter formatting chrome_browser = webbrowser.get(f'"{chrome_exe}" %s') # Open the page—this won't block your script anymore chrome_browser.open('https://www.google.com/') print('test browser')
Working Solution 2: Register the Browser Explicitly
Another reliable way is to register Chrome as a background browser type, which ensures it runs without blocking your script:
import webbrowser # Register Chrome as a background browser (non-blocking) webbrowser.register( 'chrome', None, webbrowser.BackgroundBrowser('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe') ) # Use the registered Chrome instance to open the page webbrowser.get('chrome').open('https://www.google.com/') print('test browser')
Why Your Original Code Blocked
When you used chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s', the webbrowser.get() method tried to launch the entire string as a single executable. Since %s isn't part of the actual path, this caused Python to run the browser in a synchronous, blocking mode—waiting for the browser process to exit before moving on.
In contrast, when you use webbrowser.open() with the default browser, Python automatically uses the BackgroundBrowser class, which runs the browser in the background without blocking your script.
Quick Tips
- Always wrap browser paths with spaces in double quotes (like the first solution does) to avoid path parsing errors.
- This same approach works for other browsers—just replace the Chrome executable path with Firefox, Edge, or whatever browser you need.
内容的提问来源于stack exchange,提问作者Carlos Gonzalez

