首页 > 解决方案 > 如何添加 chrome 选项以禁用 selenium 中的警报

问题描述

嘿社区我正在关注来自 freecodecamp 的 selenium 教程,我正在使用 Facebook 进行测试我正在使用 MacBook 我使用 brew 安装了我的 chromedriver

我遇到了第一个警报问题,我想禁用警报并且不知道如何将其添加到我的 chrome,因为它会自行打开而无需声明驱动程序路径请帮助所有答案显示正在声明的路径并使用 chrome 选项禁用它,但我从 Webdriver.Chrome 继承添加一个新的 chrome,例如driver = Webdriver.Chrome()每次使用下面的代码片段运行它时创建两个 chrome 实例我需要帮助使用 chromeoptions 禁用警报

import facebook.constants as const
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

class FacebookBot(webdriver.Chrome):
    """a class to control and automate a facebook bot for srappping"""
    def __init__(self, teardown=False):
        self.teardown = teardown
        super(FacebookBot, self).__init__()
       
        
        self.implicitly_wait(20)

    def __exit__(self, *args) -> None:
        if self.teardown:
            self.quit()
            return super().__exit__(*args)
         

    def facebook_homepage(self):
        """navigating the facebook scrapper bot to the facebook home page."""
        self.get(const.BASE_URL)```

标签: python-3.xseleniumselenium-webdriverweb-scrapingchrome-web-driver

解决方案


所以我在学习了更多关于课程的知识后能够通过这个......我只是希望我正在做的是pythonic所以这里是为我做了魔法的代码片段。

我将选项传递给类的 init 方法

import facebook.constants as const
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import os


class FacebookBot(webdriver.Chrome):
    """a class to control and automate a facebook bot for srappping"""
    def __init__(self, driver_path=r"/opt/homebrew/bin/chromedriver", teardown=False):
        options = Options()
        options.add_argument("--disable-notifications")
        self.driver_path = driver_path   
        os.environ["PATH"] += self.driver_path
        self.teardown = teardown
        super(FacebookBot, self).__init__(options=options)
        # self.maximize_window()
        self.implicitly_wait(20)

    def __exit__(self, *args) -> None:
        if self.teardown:
            self.quit()
            return super().__exit__(*args)
         

    def facebook_homepage(self):
        """navigating the facebook scrapper bot to the facebook home page."""
        self.get(const.BASE_URL)
   

推荐阅读