如何配置Selenium使浏览器保持开启直至用户手动关闭?
Got it, this is a super common pain point when working with Selenium—once your script finishes running, the driver instance gets cleaned up, which closes the browser automatically. Here are a few reliable ways to prevent that from happening:
1. Use the detach Experimental Option (Recommended)
This is the cleanest approach because it tells Chrome to stay attached to the browser session even after your script exits. No extra user interaction needed; the browser will stay open until you manually close it.
Modify your code like this:
from selenium import webdriver from selenium.webdriver.chrome.options import Options def main(): # Set up Chrome options chrome_options = Options() chrome_options.add_experimental_option("detach", True) driver = webdriver.Chrome(options=chrome_options) driver.maximize_window() driver.get("https://www.google.com/") main()
2. Wait for User Input
If you want to keep the browser open until you're ready to close it (like after inspecting the page), add an input() call at the end of your script. This pauses execution until you press Enter in the terminal.
from selenium import webdriver def main(): driver = webdriver.Chrome() driver.maximize_window() driver.get("https://www.google.com/") # Wait for user to press Enter before closing input("Press Enter to close the browser...") main()
3. Use a Debugging Breakpoint (For Development)
If you're actively debugging your script, setting a breakpoint at the end will pause execution and keep the browser open. Most IDEs (like VS Code, PyCharm) let you do this by clicking the gutter next to the line number, or using pdb:
import pdb from selenium import webdriver def main(): driver = webdriver.Chrome() driver.maximize_window() driver.get("https://www.google.com/") # Pause execution here pdb.set_trace() main()
Just note that this is only useful during development—you wouldn't want this in a production script.
内容的提问来源于stack exchange,提问作者Aamod Varma

