关闭

Selenium各种场景下的启动Firefox

发表于:2015-10-14 10:40

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:zhoujm928    来源:51Testing软件测试网采编

  开始学习selenium时为了启动Firefox可谓费尽周折,在大神的帮助下才堪堪搞定,走出了selenium的第一步:jdk1.8 + selenium_2.46 + Firefox国际版40.0.3。
  1、selenium启动Firefox时,默认启动一个全新的,不加载任何个人数据的浏览器,这也是最简单的:
  public void startFirefox(){
  driver = new FirefoxDriver();
  System.out.println("startFirefox.");
  }
  当然如果Firefox没有安装在默认路径下这需要我们手动设置Firefox的启动路径:
  System.setProperty("webdriver.firefox.bin", "D:/Program Files/Mozilla firefox/firefox.exe");
  WebDriver driver = newFirefoxDriver();
  2、问题随之而来,如果我们要让浏览器启动时带上我想要的某个扩展,或者是直接按照我的配置文件来启动,我们该怎么做呢?解决方法很简单,也很人性化,那 就是加载配置文件!!首先我们需要new一个Firefox的配置文件对象:FirefoxProfile,然后将我们需要的东西加入到这个文件对象中, 可以是一个插件,也可以是一个已经存在的配置文件:
  FirefoxProfile profile = new FirefoxProfile(); //创建一个Firefox的配置文件的对象
  {
  //创建需要添加的拓展或是配置文件的对象
  //将需要的拓展,已经存在的配置文件等添加到profile中,甚至是直接修改profile中的Firefox的各项参数;
  }
  FirefoxDriver driver = new FirefoxDriver(profile); //以创建的profile配置文件对象启动Firefox
  启动时加载某个特定的插件,例如Firebug
  public void startFirefoxWithPlug(){
  File plugFile = new File("file/Firebug_2.0.12.xpi");
  FirefoxProfile profile = new FirefoxProfile();
  try {
  profile.addExtension(plugFile);
  } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
  driver = new FirefoxDriver(profile);
  System.out.println("startFirefoxWithPlug.");
  }
  启动时加载默认的本地配置文件,加载默认的本地配置文件时,需要首先初始化一个配置文件:default
  public void startFirefoxWithProfile(){
  ProfilesIni profiles = new ProfilesIni();
  FirefoxProfile profile = new FirefoxProfile();
  profile = profiles.getProfile("default");
  driver = new FirefoxDriver(profile);
  System.out.println("startFirefoxWithProfile.");
  }
  启动时加载其他的配置文件:
  public void startFirefoxWithOtherProfile(){
  File profileDir = new File("Profiles/34t8j0sz.default");
  FirefoxProfile profile = new FirefoxProfile(profileDir);
  driver = new FirefoxDriver(profile);
  }
  启动时设置浏览器的参数,以设置代理为例:
  public void setProxyOfFirefox(){
  FirefoxProfile profile = new FirefoxProfile();
  profile.setPreference("network.proxy.type", 1);
  profile.setPreference("network.proxy.http", "proxyIp");
  profile.setPreference("network.proxy.http_port", "proxyPort");
  driver = new FirefoxDriver(profile);
  System.out.println("setDownloadDirOfFirefox.");
  }
  这段代码里的setPreference方法用于设置浏览器的参数,network.proxy.type则是Firefox中的配置代理相对应的字段,这些字段可以在Firefox中的about:config中看到;
  其实设置Firefox的启动很简单,只要记住Firefox启动的各种场景都是围绕这配置文件(profile)来设置的,这么一来就不需要去死记那么多的代码,了然于心自然就会了。
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号