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