始终使用Selenium在Firefox中允许地理位置

Mic*_*son 5 python selenium geolocation

我正在使用Selenium为Web应用程序创建一些端到端测试.

我正在使用Python并使用Firefox驱动程序

driver = webdriver.Firefox()

问题是我的网络应用程序使用HTML5地理位置,似乎每次运行我的测试时,我都必须点击Firefox中的"允许位置"弹出窗口,使我的测试不是自动化的.

有没有办法强制Selenium Firefox驱动程序始终允许地理定位而不提示?

小智 7

您可以强制浏览器返回某些预定义位置而无需权限请求.

只需执行以下JavaScript代码:

"navigator.geolocation.getCurrentPosition = function(success) { success({coords: {latitude: 50.455755, longitude: 30.511565}}); }"
Run Code Online (Sandbox Code Playgroud)

在Firefox和Chrome中测试过.


Hen*_*k F 6

截至撰写本文时(4 月 20 日),这个问题已经有近 7 年历史了,但随着 API 的变化,它仍然具有相关性。我在使用 Selenium 编写功能测试时遇到了类似的问题。

例如,规范Mozilla 示例中可能发生的场景:

  • 该浏览器不支持地理定位 ( !navigator.geolocation)
  • 支持地理定位 ( getCurrentPosition(success, error))
    • 访问地理位置被拒绝 ( error)
    • 允许访问地理位置 ( success)

以下是这些场景如何转换为 Selenium 设置:

from selenium import webdriver

# geolocation API not supported
geoDisabled = webdriver.FirefoxOptions()
geoDisabled.set_preference("geo.enabled", False)
browser = webdriver.Firefox(options=geoDisabled)
Run Code Online (Sandbox Code Playgroud)

为了沿着模拟“不允许”的路径,单击支持地理的浏览器的提示(默认情况下启用,通过检查about:config):

# geolocation supported but denied
geoBlocked = webdriver.FirefoxOptions()
geoBlocked.set_preference("geo.prompt.testing", True)
geoBlocked.set_preference("geo.prompt.testing.allow", False)
browser = webdriver.Firefox(options=geoBlocked)
Run Code Online (Sandbox Code Playgroud)

最后,模拟“允许位置访问”单击

# geolocation supported, allowed and location mocked
geoAllowed = webdriver.FirefoxOptions()
geoAllowed.set_preference('geo.prompt.testing', True)
geoAllowed.set_preference('geo.prompt.testing.allow', True)
geoAllowed.set_preference('geo.provider.network.url',
    'data:application/json,{"location": {"lat": 51.47, "lng": 0.0}, "accuracy": 100.0}')
browser = webdriver.Firefox(options=geoAllowed)
Run Code Online (Sandbox Code Playgroud)

geo.wifi.uri属性似乎不再存在,而是改为了geo.provider.network.url。此解决方案还可以防止从磁盘加载“随机”Firefox 配置文件,或在运行时执行 JS 代码来模拟位置。浏览器配置是通过“Options”(正如本解决方案的情况)、“Profiles”还是通过“DesiredCapativity”设置,在很大程度上无关紧要。我发现选项是最简单的。


Dar*_*rin 0

我相信默认设置是使用新的匿名配置文件启动 Firefox。您可以使用 -Dwebdriver.firefox.profile=whatever 启动 selenium,其中“whatever”是启动 firefox -P 时配置文件的名称。

为了确保持久登录和其他 cookie 不会出现奇怪的情况:

  • 使用“firefox -P”启动 Firefox
  • 选择您将用于启动测试的配置文件
  • 编辑 -> 首选项 -> 隐私,选择使用历史记录的自定义设置
  • 告诉 Firefox 保留 cookie,直到“我关闭 Firefox”