在使用 Selenium WebDriver 进行自动化测试时,默认情况下,当脚本执行完毕后,WebDriver 会自动关闭浏览器。如果你希望阻止这一行为,可以通过以下几种方法实现:
detach
选项(适用于 Chrome 和 Edge)对于 Chrome 和 Edge 浏览器,可以使用 detach
选项来保持浏览器打开状态。
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
service = Service('path/to/chromedriver')
driver = webdriver.Chrome(service=service, options=chrome_options)
# 执行你的自动化脚本
driver.get('https://www.example.com')
# 脚本执行完毕后,浏览器不会关闭
no-sandbox
和 disable-dev-shm-usage
选项这些选项可以帮助解决某些环境下的权限问题,并且有时也能间接帮助保持浏览器打开。
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
atexit
模块阻止关闭你可以使用 Python 的 atexit
模块来注册一个函数,在程序退出时阻止浏览器关闭。
import atexit
from selenium import webdriver
driver = webdriver.Chrome()
def keep_browser_open():
pass
atexit.register(keep_browser_open)
# 执行你的自动化脚本
driver.get('https://www.example.com')
# 脚本执行完毕后,浏览器不会关闭
你可以在脚本的最后不调用 driver.quit()
或 driver.close()
,这样浏览器就不会自动关闭。
from selenium import webdriver
driver = webdriver.Chrome()
# 执行你的自动化脚本
driver.get('https://www.example.com')
# 不调用 driver.quit() 或 driver.close()
通过上述方法,你可以有效地阻止 Selenium WebDriver 在脚本执行完毕后关闭浏览器。选择适合你具体需求的方法进行实现即可。
领取专属 10元无门槛券
手把手带您无忧上云