[Selenium] HTML5 中的 Geolocation

在 HTML5 ,新特性 Geolocation 用于定位用户位置信息。

由于用户位置信息是敏感信息,所以需要得到用户允许后,才能让程序通过 API  获取当前用户信息。WebDriver 程序每次重新允许都是新的会话进程,及时之前在浏览器中已经通过手工方式运行浏览器访问用户的位置信息,但在当前运行环境中依旧无法获取之前用户设置。解决方法是让浏览器每次执行 WebDriver 测试程序时,依旧加载之前用户设置即可。

以Firefox 为例,在Mac OS 平台上,可通过如下命令打开用户 Profile 管理器

$ /Applications/Firefox.app/Contents/MacOS/firefox-bin -ProfileManager

其他平台打开方式查询官方开发者文档:

https://developer.mozilla.org/en-US/docs/Mozilla/Multiple_Firefox_Profiles

创建 geolocation Profile 成功后,单击 Start Firefox 启动 Firefox 浏览器。

 

以 http://www.weschools.com/html/html5_geolocation.asp 为例。为演示完整的示例代码,还需创建一个包含 Geolocation 信息的 JSON 文件,这里命名为 location.json,内容如下:

{

  "status":"OK",

  "accuracy":10.0,

  "location":{"lat":52.1771129, "lng":5.4}

}

示例:

package com.learningselenium.html5;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.firefox.FirefoxProfile;

import org.openqa.selenium.firefox.internal.Profileslni;

import  org.testng.annotations.*;

 

public class testHTML5Geolocation{

  private static WebDriver driver;

 

  @BeforeClass

  public void setUp() throws Exception{

    //获取geolocation Profile

    FirefoxProfile profile = new Profileslni().getProfile("geolocation");

    //配置Geolocation 信息

    profile.setPreference("geo.wifi.uri", "/Selenium 2/mydoc/codes/4/location.json");

    //通过定制 profile 启动浏览器

    driver = new FirefoxDriver(profile);

    driver.get("http://www.weschools.com/html/html5_geolocation.asp");

  }

 

  @Test

  public void testGetLocation() throws Exception{

    driver.findElement(By.cssSelector("p#demo button")).click();

  }

 

  @AfterClass

  public void tearDown() throws Exception{

    driver.quit();

  }

}

posted @ 2015-06-05 15:45  *飞飞*  阅读(363)  评论(0编辑  收藏  举报