使用Selenium ChromeDriver关闭Facebook通知无效的问题求助
解决Facebook自动化脚本中Chrome通知弹窗阻塞问题
你的代码核心问题是初始化Chrome驱动时没有传入配置好的chrome_options,导致你设置的通知权限规则根本没被浏览器应用,所以弹窗依然会出现。
修正后的代码
把配置好的chrome_options传入webdriver.Chrome()的参数中,同时可以补充几个额外的参数来进一步避免各类弹窗:
from selenium import webdriver from selenium.webdriver.common.keys import Keys from webdriver_manager.chrome import ChromeDriverManager import time from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.chrome.service import Service chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--disable-infobars") chrome_options.add_argument("--disable-popup-blocking") # 禁用弹窗拦截 chrome_options.add_argument("--disable-notifications") # 直接禁用通知 chrome_options.add_experimental_option("prefs", { "profile.default_content_setting_values.notifications": 2, "profile.default_content_setting_values.popups": 2 # 禁止弹窗 }) s = Service(ChromeDriverManager().install()) # 关键:把chrome_options传入驱动初始化 driver = webdriver.Chrome(service=s, options=chrome_options) driver.get('https://www.facebook.com/login/') time.sleep(1) driver.maximize_window()
备用方案:如果弹窗仍出现,手动定位关闭
如果上述配置还是无法阻止弹窗,可以添加显式等待,定位弹窗的关闭按钮并点击:
# 在driver.get()之后添加这段代码 try: # 根据弹窗的关闭按钮定位器调整,这里假设是X按钮的xpath close_btn = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), '关闭') or contains(@aria-label, '关闭')]")) ) close_btn.click() except: # 没有弹窗就跳过 pass
内容的提问来源于stack exchange,提问作者Ahmed Ibrahim
相关产品推荐
相关产品推荐

