如何使用Python版Selenium获取WebDriver发送的桌面通知文本?
测试WebDriver推送通知的可行方案
Chrome浏览器实现方案
配置ChromeOptions开启通知权限
from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() # 直接授予通知权限 chrome_options.add_experimental_option("prefs", { "profile.default_content_setting_values.notifications": 1 }) driver = webdriver.Chrome(options=chrome_options)通过Chrome DevTools Protocol(CDP)捕获通知数据
利用CDP监听浏览器日志,直接提取通知的标题、内容等信息:# 启用Log域监听 driver.execute_cdp_cmd("Log.enable", {}) # 定义捕获回调 def capture_notification(message): if message["message"]["source"] == "notification": note_data = message["message"]["params"]["notification"] print("通知标题:", note_data["title"]) print("通知内容:", note_data["message"]) # 添加日志监听 driver.add_cdp_listener("Log.entryAdded", capture_notification) # 触发推送通知的页面操作 driver.get("目标页面URL")
Firefox浏览器实现方案
配置FirefoxOptions授予通知权限
from selenium import webdriver from selenium.webdriver.firefox.options import Options firefox_options = Options() firefox_options.set_preference("permissions.default.desktop-notification", 1) driver = webdriver.Firefox(options=firefox_options)通过注入JS监听通知创建事件
在页面中覆盖Notification构造函数,捕获通知的完整数据:# 注入监听脚本 driver.execute_script(""" window.capturedNotes = []; const OriginalNote = window.Notification; window.Notification = function(title, opts) { const note = new OriginalNote(title, opts); window.capturedNotes.push({title, ...opts}); return note; }; Object.assign(window.Notification, OriginalNote); """) # 触发通知后提取数据 notes = driver.execute_script("return window.capturedNotes;") for item in notes: print("通知标题:", item["title"]) print("通知内容:", item["body"])
通用注意事项
- 确保WebDriver与浏览器版本严格匹配,避免权限配置失效
- 部分网站需完成登录、页面交互后才会触发推送,需提前处理前置操作
- Headless模式下,Chrome需使用
--headless=new参数,Firefox需设置headless: true,同时保持权限配置不变

内容的提问来源于stack exchange,提问作者Arsen Kishmiryan
相关产品推荐
相关产品推荐

