selenium中各种场景下启动Firefox

来源:互联网 发布:最好的日语翻译软件 编辑:程序博客网 时间:2024/06/10 03:33

  开始学习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

  1. 启动时加载某个特定的插件,例如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 blocke.printStackTrace();}driver = new FirefoxDriver(profile);System.out.println("startFirefoxWithPlug.");}
  1. 启动时加载默认的本地配置文件,加载默认的本地配置文件时,需要首先初始化一个配置文件:default
public void startFirefoxWithProfile(){ProfilesIni profiles = new ProfilesIni();FirefoxProfile profile = new FirefoxProfile();profile = profiles.getProfile("default");driver = new FirefoxDriver(profile);System.out.println("startFirefoxWithProfile.");}
  1. 启动时加载其他的配置文件:
public void startFirefoxWithOtherProfile(){File profileDir = new File("Profiles/34t8j0sz.default");FirefoxProfile profile = new FirefoxProfile(profileDir);driver = new FirefoxDriver(profile);}
  1. 启动时设置浏览器的参数,以设置代理为例:
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中看到;
0 0
原创粉丝点击