selenium 启动 chrome 自动关闭
时间: 2023-09-15 14:03:20 浏览: 369
使用Selenium启动Chrome并自动关闭可以通过以下步骤实现:
1. 首先,确保已经安装了Chrome浏览器以及ChromeDriver驱动程序,并将它们添加到系统的环境变量中。
2. 在Python脚本中导入Selenium库:
```python
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
```
3. 创建ChromeOptions对象并添加自定义配置以实现自动关闭Chrome。可以使用以下代码:
```python
chrome_options = Options()
chrome_options.add_argument("--no-sandbox") # 避免启动报错
chrome_options.add_argument("--headless") # 以无头模式启动
chrome_options.add_argument("--disable-gpu") # 禁用GPU加速
```
可以根据需求添加其他配置选项。
4. 使用以上配置创建ChromeDriver对象:
```python
driver = webdriver.Chrome(chrome_options=chrome_options)
```
这将以自动关闭的方式启动Chrome浏览器。
5. 可以在此基础上编写自动化测试或爬虫脚本,对网页进行操作。
6. 执行完毕后,关闭Chrome浏览器:
```python
driver.quit()
```
使用`quit()`方法而不是`close()`方法,确保Chrome浏览器完全关闭。
通过以上步骤,你可以使用Selenium启动Chrome并在操作完成后自动关闭Chrome浏览器。
阅读全文
相关推荐


















