截至撰写本文时(4 月 20 日),这个问题已经有将近 7 年的历史了,但随着 API 的变化,它仍然具有相关性。我在使用 Selenium 编写功能测试时遇到了类似的问题。
例如,规范Mozilla example 中可能出现的场景:
- 浏览器不支持地理定位 (
!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)
为了在启用地理的浏览器的提示中模拟“不允许”单击的路径(默认情况下启用,通过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)
最后,模拟“允许位置访问”点击
# 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)
geo.wifi.uri 属性似乎不再存在,而是改为geo.provider.network.url。该解决方案还可以防止从磁盘加载“随机” Firefox 配置文件,或者在运行时执行 JS 代码来模拟该位置。浏览器配置是通过“选项”(与此解决方案一样)、“配置文件”还是通过"DesiredCapabilities" 设置的,这在很大程度上无关紧要。我发现 Options 是最简单的。