如何在 Python 中处理 Selenium Chrome WebDriver 通知?
已尝试忽略/接受
alert
和active element
,但似乎通知必须以其他方式处理。另外,所有的 Google 搜索结果都在驱使我寻找我并不真正需要的 Java 解决方案。我是 Python 新手。
提前致谢。
您可以使用 Chrome 选项禁用浏览器通知。
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs",prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)
2021 年 12 月,使用 ChromeDriver 版本:96,python 代码结构如下所示,用于处理 ChromeDriver/浏览器通知:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# Creating Instance
option = Options()
# Working with the 'add_argument' Method to modify Driver Default Notification
option.add_argument('--disable-notifications')
# Passing Driver path alongside with Driver modified Options
browser = webdriver.Chrome(executable_path= your_chrome_driver_path, chrome_options= option)
# Do your stuff and quit your driver/ browser
browser.get('https://www.google.com')
browser.quit()
按照以下代码使用Python selenium处理通知设置
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
option = Options()
option.add_argument("--disable-infobars")
option.add_argument("start-maximized")
option.add_argument("--disable-extensions")
option.add_experimental_option("prefs",
{"profile.default_content_setting_values.notifications": 2
})
注1-允许通知,2-阻止通知
上面 16 年 12 月的答案在 2020 年 8 月对我来说不起作用。我相信 Selenium 和 Chrome 都已经改变了。
我正在使用 Chrome 84 的二进制文件,该二进制文件被列为当前版本,尽管
selenium.dev
提供了适用于 Chrome 85 的二进制文件。我必须假设这是一个测试版,因为我没有其他信息。
到目前为止我只有部分答案,但我相信以下两行是正确的方向。这是我今晚所了解到的。我有一个向 Facebook 打开的测试窗口,并且问题中显示了确切的窗口。上面 pythonjar 2016 年 12 月 30 日的答案中给出的代码为我生成了错误消息。这些代码行没有错误,所以我相信这是正确的轨道。
>>> from selenium.webdriver import ChromeOptions
>>> chrome_options = ChromeOptions()
如果我有时间的话,我明天会更新。
抱歉回答不完整。我希望尽快完成它。我希望这有帮助。如果你先到达那里,请告诉我。
使用 Chrome Versa 85.0.4183.83(Versão 官方)64 位和 ChromeDriver 85.0.4183.83
这是代码,它正在工作:
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs",prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("https://www.google.com/")
2020/08/27
如果您正在使用 selenium 4.x ,这些是您想要考虑的修改:
from selenium import webdriver
options = webdriver.ChromeOptions()
# Working with the 'add_argument' Method to modify Driver Default Notification
options.add_argument('--disable-notifications')
# Passing Driver path alongside with Driver modified Options
driver = webdriver.Chrome(options=options)
路径
executable_path
可以留空,它会自动下载到~/.cache/selenium
或使用此修改:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
options = webdriver.ChromeOptions()
service = Service(executable_path=CHROMEDRIVER_PATH)
driver = webdriver.Chrome(service=service, options=options)
这是我在这里找到的。