始终允许在Firefox中使用Selenium进行地理定位

2024-10-01 11:19:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

driver = webdriver.Firefox()

问题是我的web应用程序使用HTML5地理位置,而且似乎每次我运行测试时,我都必须单击Firefox中的“allowlocation”弹出窗口,这使得我的测试不那么自动化。在

有没有一种方法可以强制Selenium Firefox驱动程序在不提示的情况下始终允许地理定位?在


Tags: 方法定位web应用程序driverselenium驱动程序情况
3条回答

因为在这个问题被问到三年后,我又遇到了同样的问题,而且上面的答案都不让我满意。我喜欢展示我使用的解决方案。在

所以我在this blog上找到了答案。在

在我的python代码中这样使用它:

@classmethod
def setUpClass(cls):
    cls.binary = FirefoxBinary(FF_BINARY_PATH)
    cls.profile = FirefoxProfile()
    cls.profile.set_preference("geo.prompt.testing", True)
    cls.profile.set_preference("geo.prompt.testing.allow", True)
    cls.profile.set_preference('geo.wifi.uri', GEOLOCATION_PATH)
    cls.driver = Firefox(firefox_binary=cls.binary, firefox_profile=cls.profile)

GEOLOCATION_PATH上是JSON文件的路径:

^{pr2}$

您可以在没有权限的情况下强制返回某些预定义的位置请求。在

只需执行以下JavaScript代码:

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

在Firefox和Chrome中测试过。在

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

要确保持续登录和其他cookies没有任何奇怪之处:

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

相关问题 更多 >