首页 > 解决方案 > Python Selenium 分离选项不起作用

问题描述

我想使用 Selenium 和 Chrome 编写一个 Python 脚本,其中 Selenium 在脚本完成时不会关闭 Chrome 浏览器。从做一堆谷歌搜索来看,标准解决方案似乎是使用分离选项。但是当我运行以下脚本时:

import selenium
from selenium import webdriver

from selenium.webdriver.chrome.options import Options
chrome_options = Options() 
chrome_options.add_experimental_option("detach", True)

driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.google.com/")

它会打开 Chrome,转到 Google 的主页,然后关闭浏览器。它不会引发任何错误。

知道为什么它不起作用吗?我在 Windows 10 上使用最新版本的 Google Chrome,并且安装了最新版本的 selenium 模块。我在网上找不到任何说实验性分离选项不再存在的东西。我仔细检查了API,它看起来是正确的语法。

标签: pythonseleniumselenium-webdriver

解决方案


我发现了另一种方法:在远程调试模式下启动 Chrome,然后连接到它。这样,不仅浏览器保持打开状态,而且您还可以使用现有的 Chrome 配置文件,这样您就可以利用 cookie 允许您访问的任何站点,而无需在每次运行脚本时登录。

如果您使用的是 Windows 10,则需要执行以下操作:

  1. 远程启动 Google Chrome,指向您现有的用户配置文件和您要使用的端口:
cd "C:\Program Files (x86)\Google\Chrome\Application"
chrome.exe -remote-debugging-port=9014 --user-data-dir="%LOCALAPPDATA%\Google\Chrome\User Data"
  1. 在您的 python 脚本中,连接到运行此版本 Chrome 的本地端口:
import selenium
from selenium import webdriver

from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "localhost:9014")
driver = webdriver.Chrome(options=chrome_options)

driver.get("https://github.com/")

推荐阅读