Python中如何通过类向Selenium Chrome驱动传递Options参数
解决方案
你只需要在自定义Browser类的初始化流程中提前配置好Chrome Options实例,调用父类构造方法时将配置对象作为参数传入即可,修改后的可运行代码如下:
import os from selenium import webdriver from selenium.webdriver.chrome.options import Options class Browser(webdriver.Chrome): def __init__(self, headless: bool = True): self.driver_path = r"path/to/executable/file" os.environ['PATH'] += os.pathsep + self.driver_path # 构建Chrome启动配置 chrome_options = Options() if headless: chrome_options.add_argument('--headless') # 无头模式下建议补充这两个参数,规避Linux/容器环境的启动报错 chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') # 调用父类构造传入配置:Selenium 4.x 版本参数名为options,3.x旧版本参数名为chrome_options super().__init__(options=chrome_options) def some_function(self): # 自定义方法逻辑 pass
注意事项
- 如果你使用的是Selenium 3.x旧版本,将父类初始化的入参从
options=chrome_options替换为chrome_options=chrome_options即可 - 你当前将驱动路径加入系统
PATH环境变量的写法是有效的,Selenium会自动从环境变量路径中查找匹配的Chrome驱动,不需要额外传入executable_path参数 - 初始化Browser实例时如果需要关闭无头模式,只要传入
headless=False即可,灵活度更高
内容的提问来源于stack exchange,提问作者Mathieu P
相关产品推荐
相关产品推荐

