在使用 selenium 进行 webdriver 测试时,浏览器在调用完后将会自动关闭,即使没有调用 "driver.close()"。
有时候,可能需要特意将 浏览器保持开启状态,此时需要使用 detach 参数
# 'detach' = True 将不会自动关闭 options.add_experimental_option('detach', True)
具体示例代码如下:
from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService options = webdriver.ChromeOptions() pref_dict = {"profile.default_content_settings.popups": 0, # "download.default_directory": self.download_path, "safebrowsing.enabled": True } options.add_experimental_option('prefs', pref_dict) # 'detach' = True 将不会自动关闭 options.add_experimental_option('detach', True) # 加载驱动,适配 selenium 4 chrome_service = ChromeService(executable_path=r"D:\Program Files (x86)\Python311\chromedriver.exe") get_driver = webdriver.Chrome(options=options, service=chrome_service) class WebService: def prepare_env(self, url): get_driver.get(url) if __name__ == '__main__': sc = WebService() sc.prepare_env("http://www.baidu.com")
标签:__,webdriver,浏览器,selenium,detach,True,options From: https://www.cnblogs.com/bruce-he/p/17936459.html