为什么selenium运行完,会自动关闭浏览器
时间: 2023-08-16 20:41:20 浏览: 347
Selenium 在运行结束后会自动关闭浏览器,这是因为 Selenium 在启动浏览器时,会创建一个 WebDriver 实例,该实例会与浏览器建立一个连接。在程序运行结束时,Selenium 会关闭浏览器,并断开与 WebDriver 实例的连接,从而释放资源。
如果不希望 Selenium 在运行结束后自动关闭浏览器,可以使用如下的方法:
```python
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver import Chrome
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
chromedriver_path = "path/to/chromedriver"
service = Service(executable_path=chromedriver_path)
driver = Chrome(service=service, options=chrome_options)
driver.get("https://www.baidu.com")
search_box = driver.find_element_by_id("kw")
search_box.send_keys("Python")
search_box.send_keys(Keys.RETURN)
```
在这个示例中,我们使用了 ChromeOptions 对象的 add_experimental_option() 方法,将 detach 设置为 True。这样在程序运行结束后,浏览器窗口不会自动关闭,需要手动关闭。
需要注意的是,如果设置了 detach 为 True,需要手动关闭浏览器窗口,否则可能会占用系统资源。同时,如果使用了无头模式(headless mode),则无法手动关闭浏览器窗口,只能通过 kill 命令来关闭。