selenium中配置FirefoxProfile控制文件下载路径、SSL和Proxy

来源:互联网 发布:p图 淘宝刷手 编辑:程序博客网 时间:2024/06/05 07:49

前面一篇文章我有讲到可以利用Robot来控制Firefox下载后弹出的窗口的操作从而实现对文件的下载。但是,往往这会存在一些问题。比如如果想更改文件存放的位置,路径输入靠按键很麻烦。还有如果默认的下载路径并不存在的话,又会弹出错误窗口。所以这个问题,需要寻求更有效的解决办法。

这对于我们思考来说,第一步就会想到是否可以更改下载默认路径。好在通过设置FirefoxProfile即可以达到这个目的(参考:http://stackoverflow.com/questions/1176348/access-to-file-download-dialog-in-firefox)。于是我们就可以添加如下代码设置。

        FirefoxProfile firefoxProfile = new FirefoxProfile();        firefoxProfile.setPreference("browser.download.folderList",2);        firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);        firefoxProfile.setPreference("browser.download.dir","/tmp");        //firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv,application/vnd.ms-excel");

接着,我们需要启动WebDriver。提供的构造函数参考RemoteWebDriver(http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/remote/RemoteWebDriver.html)以及FirefoxDriver(http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/firefox/FirefoxDriver.html)

而对于某些版本的selenium服务器,当访问https时候,会出现“Untrusted SSL certificate”问题。这时候我们也可以借助于FirefoxProfile设置来接受它。参考:http://abodeqa.wordpress.com/2013/05/03/accepting-untrusted-ssl-certificate-in-webdriver-for-chrome-and-firefox-browser/


现在我们更多的用DesiredCapabilities参数来构造webdrivier,而DesiredCapabilities可以设置proxy。

            Proxy proxy = new Proxy();            proxy.setProxyType(ProxyType.MANUAL);            proxy.setHttpProxy("proxy-host:proxy-port");            proxy.setSslProxy("proxy-host:proxy-port");            capabilities.setCapability(CapabilityType.PROXY, proxy);
DesiredCapabilities的功能很强大,还可以设置FirefoxProfile。
DesiredCapabilities capabilities = DesiredCapabilities.firefox();capabilities.setCapability(FirefoxDriver.PROFILE, firefoxProfile);  
当对DesiredCapabilities初始化完成后就可以用它来构造FirefoxDriver和RemoteWebDriver了(http://stackoverflow.com/questions/6048276/how-to-set-firefox-profile-using-remotewebdriver-net)。

browserDriver = new FirefoxDriver(capabilities);browserDriver = new RemoteWebDriver(new URL("http://" + seleniumHost + ":" + seleniumPort + "/wd/hub"), capabilities);


注:关于FirefoxDriver和RemoteWebDriver的区别,可以参考如下话。

If you want to use the browser on the machine that is running the automation, then you can use everything but RemoteWebDriver.

RemoteWebDriver requires the selenium-server-standalone to be running (the others do not). This could be running on the same machine or a "remote" one.

If you want to use Grid (which is run via selenium-server-standalone) then you *must* use RemoteWebDriver.

https://groups.google.com/forum/#!topic/webdriver/4h7YWWOQ60M
原创粉丝点击