看起来你的问题包含两个部分。你正在尝试弄清 webdriver 和用户配置文件路径。让我为你回答这两个问题。
在最新版本的 Selenium 中,executable_path
参数已被弃用。现在需要包含可执行路径的服务对象。有两个选项:
服务对象
选项一:使用你的可执行路径
将此导入附加到你的代码中:
from selenium.webdriver.chrome.service import Service
然后,将服务对象包含在代码中:
driver = webdriver.Chrome(service=Service("C:\Program Files\Google\Chrome\Application\chrome.exe"))
选项 #2:让 Web Driver Manager 处理它
当驱动程序变得过时时,这非常方便。无需重新下载驱动程序。
首先,在终端中进入项目目录。如果您使用的是 PyCharm,则无需遍历目录,因为您已经在项目目录中。
使用 pip 安装 Web Driver Manager:
pip install webdriver_manager
现在,无需输入可执行路径:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://www.facebook.com")
选择用户配置文件
这非常简单。首先,打开 Chrome 并在 URL 地址栏中输入 chrome://version/
,您将看到配置文件路径。它看起来像这样:C:\Users\yourprofile\AppData\Local\Google\Chrome\User Data\Default
。
然后,将以下 Chrome 选项包括如下:
options = webdriver.ChromeOptions()
options.add_argument(r"--user-data-dir=C:\Users\yourprofile\AppData\Local\Google\Chrome\User Data")
options.add_argument(r"--profile-directory=Default")
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
Chrome(path)
,但在下一个版本中,如果您不使用Chrome(service=Service(path))
,它可能会引发错误(并停止程序)。 - furas