首页 > 解决方案 > 如何在 Python Selenium 中以 Chrome 隐身模式允许位置和通知?

问题描述

我想在隐身模式下允许 Chrome 上的位置和通知使用Selenium.

这是我的代码:

import selenium
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
option = Options()

option.add_argument("--incognito")
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":1,
    "profile.default_content_setting_values.geolocation": 1,
})

driver = webdriver.Chrome(options=option, executable_path="path/to/executable")

option.add_argument("--incognito")如果不包含此代码(浏览器以正常模式打开),则此代码有效(启用通知和位置)。为什么会发生这种情况,我该如何启用这些以及隐身模式?

注意:您可以通过打开请求您的位置的网站来检查该位置是否已启用。

浏览器的隐身视图: 在此处输入图像描述

标签: pythonseleniumselenium-chromedriver

解决方案


Asil Açku 根据您的问题和您的评论,我没有确定您要完成的工作。

下面的代码使用Selenium以隐身模式打开 Chrome 浏览器。 正在访问的网站是具有精确地理位置的谷歌地图。页面加载后,Google 会自动获取我的当前位置。它在没有浏览器通知的情况下执行此操作。

如果这不是您需要的,请提供更多详细信息。

from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium import webdriver

capabilities = DesiredCapabilities().CHROME

chrome_options = Options()
chrome_options.add_argument("--incognito")
chrome_options.add_argument("--disable-infobars")
chrome_options.add_argument("start-maximized")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-popup-blocking")

prefs = {
    'profile.default_content_setting_values':
    {
        'notifications': 1,
        'geolocation': 1
    },

    'profile.managed_default_content_settings':
    {
        'geolocation': 1
    },
}

chrome_options.add_experimental_option('prefs', prefs)
capabilities.update(chrome_options.to_capabilities())

driver = webdriver.Chrome('/usr/local/bin/chromedriver', options=chrome_options)

url='https://www.google.com/maps/@48.1152117,-1.6634771,12.79z/data=!5m1!1e1'
driver.get(url)

# time used only for testing
time.sleep(10)

您在 Google 地图中提到了有关“分享您的实时位置”的内容。由于您想以隐身模式打开 Chrome,因此此功能不可用。在这种隐身模式下,您的位置历史记录或共享位置信息将不会与您共享此信息的任何人一起更新。

Chrome 中的 Google 地图位置共享 在此处输入图像描述

隐身模式下的 Google 地图位置共享 在此处输入图像描述


推荐阅读