Selenium执行后Chrome标签页自动关闭:如何保持标签页开启?
解决Selenium Chrome执行后自动关闭的问题
你的代码执行完成后浏览器立即关闭,是因为Python脚本运行结束时,driver对象被销毁,触发了浏览器的关闭动作。以下两种方法可以让浏览器保持开启状态:
方法1:添加手动等待
在脚本末尾添加输入等待,让程序暂停执行,直到你手动输入内容后才结束,这样浏览器就会一直保持打开:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys driver_service=Service(executable_path=r'./chromedriver.exe') driver = webdriver.Chrome(service=driver_service) driver.get('https://google.com') driver.find_element(By.NAME, 'q').send_keys('word'+Keys.RETURN) # 添加这行,等待用户输入后才结束程序 input("按任意键关闭浏览器...")
方法2:启用Chrome的detach模式
通过ChromeOptions添加detach实验性选项,让浏览器在脚本执行完毕后继续运行,不需要手动干预:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys # 配置Chrome选项 chrome_options = Options() chrome_options.add_experimental_option("detach", True) driver_service=Service(executable_path=r'./chromedriver.exe') # 初始化driver时传入options参数 driver = webdriver.Chrome(service=driver_service, options=chrome_options) driver.get('https://google.com') driver.find_element(By.NAME, 'q').send_keys('word'+Keys.RETURN)
注意:你的原代码缺少By和Keys的导入,上面的示例已经补充了这部分,否则运行时会报错。
内容的提问来源于stack exchange,提问作者Abdo Rahal
相关产品推荐
相关产品推荐

