如何解决 Python Selenium 中的“选项未定义错误”?

问题描述

我最近遇到了一个问题,在使用 Selenium 时,我想使用我的认 chrome 浏览器配置文件,因此它已登录和所有内容,但是在 google 上搜索时,它给了我一个代码,基本上是这样的:

chrome_options = Options()
chrome_options.add_argument("[path to the profile]")
driver = webdriver.Chrome(chrome_options=chrome_options,executable_path=[path to the webdriver])

我遇到的错误是:

NameError: name 'Options' is not defined

我该如何解决这个问题,也许有更好的方法来加载 chrome 配置文件

解决方法

有两件事。可能您没有为 Options 导入所需的模块。因此,要使用 Options 的实例,您必须包含以下 import

from selenium.webdriver.chrome.options import Options

此外,chrome_options 已弃用,您必须改用 options。所以你的有效代码块将是:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("[path to the profile]")
driver = webdriver.Chrome(options=chrome_options,executable_path=[path to the webdriver])
,

您需要将 Options 导入命名空间:

from selenium.webdriver.chrome.options import Options

chrome_options = Options()