開始學習selenium時為了啟動Firefox可謂費盡周折,在大神的幫助下才堪堪搞定,走出了selenium的第一步:jdk1.8 + selenium_2.46 + Firefox國際版40.0.3。
1、selenium啟動Firefox時,默認啟動一個全新的,不加載任何個人數(shù)據(jù)的瀏覽器,這也是簡單的:
public void startFirefox(){
driver = new FirefoxDriver();
System.out.println("startFirefox.");
}
當然如果Firefox沒有安裝在默認路徑下這需要我們手動設(shè)置Firefox的啟動路徑:
System.setProperty("webdriver.firefox.bin", "D:/Program Files/Mozilla firefox/firefox.exe");
WebDriver driver = newFirefoxDriver();
2、問題隨之而來,如果我們要讓瀏覽器啟動時帶上我想要的某個擴展,或者是直接按照我的配置文件來啟動,我們該怎么做呢?解決方法很簡單,也很人性化,那 是加載配置文件!!首先我們需要new一個Firefox的配置文件對象:FirefoxProfile,然后將我們需要的東西加入到這個文件對象中, 可以是一個插件,也可以是一個已經(jīng)存在的配置文件:
FirefoxProfile profile = new FirefoxProfile(); //創(chuàng)建一個Firefox的配置文件的對象
{
//創(chuàng)建需要添加的拓展或是配置文件的對象
//將需要的拓展,已經(jīng)存在的配置文件等添加到profile中,甚至是直接修改profile中的Firefox的各項參數(shù);
}
FirefoxDriver driver = new FirefoxDriver(profile); //以創(chuàng)建的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);
}
啟動時設(shè)置瀏覽器的參數(shù),以設(shè)置代理為例:
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方法用于設(shè)置瀏覽器的參數(shù),network.proxy.type則是Firefox中的配置代理相對應(yīng)的字段,這些字段可以在Firefox中的about:config中看到;
其實設(shè)置Firefox的啟動很簡單,只要記住Firefox啟動的各種場景都是圍繞這配置文件(profile)來設(shè)置的,這么一來不需要去死記那么多的代碼,了然于心自然會了。