用selenium下载图片java代码

参考http://ardesco.lazerycode.com/index.php/2012/07/how-to-download-files-with-selenium-and-why-you-shouldnt/

修改了一部分,从http://image.baidu.com/search/detail?ct=503316480&z=0&ipn=false&word=%E5%A4%B4%E5%83%8F%20%E5%8F%AF%E7%88%B1&pn=5&spn=0&di=48693053420&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=&ie=utf-8&oe=utf-8&in=3354&cl=2&lm=-1%2C&st=&cs=2390703471%2C168602444&os=2076211555%2C1322829468&adpicid=0&ln=2000&fr=ala&fmq=1378374347070_R&ic=0&s=0%2C&se=&sme=&tab=&face=&ist=&jit=&statnum=head&cg=head&bdtype=0&objurl=http%3A%2F%2Fimg5.duitang.com%2Fuploads%2Fitem%2F201403%2F14%2F20140314121845_8iTiY.thumb.700_0.jpeg&fromurl=http%3A%2F%2Fwww.duitang.com%2Fpeople%2Fmblog%2F204985052%2Fdetail%2F&gsm=0   这一张图开始,找到图片的src地址,下载的图片都放在了E:\素材\pictures\downloads目录下

主要代码如下所示:

FileDownloader类

[java]  view plain  copy
  1. package com.test.filedownloader;  
  2.   
  3. import org.apache.commons.io.FileUtils;  
  4. import org.apache.http.HttpResponse;  
  5. import org.apache.http.client.HttpClient;  
  6. import org.apache.http.client.methods.HttpGet;  
  7. import org.apache.http.client.params.ClientPNames;  
  8. import org.apache.http.client.protocol.ClientContext;  
  9. import org.apache.http.impl.client.BasicCookieStore;  
  10. import org.apache.http.impl.client.DefaultHttpClient;  
  11. import org.apache.http.impl.cookie.BasicClientCookie;  
  12. import org.apache.http.params.HttpParams;  
  13. import org.apache.http.protocol.BasicHttpContext;  
  14. import org.openqa.selenium.Cookie;  
  15. import org.openqa.selenium.WebDriver;  
  16. import org.openqa.selenium.WebElement;  
  17.    
  18.   
  19. import com.test.MyLog;  
  20.   
  21. import java.io.File;  
  22. import java.io.IOException;  
  23. import java.net.URISyntaxException;  
  24. import java.net.URL;  
  25. import java.util.Set;  
  26.   
  27. public class FileDownloader {  
  28.     private WebDriver driver;  
  29. //    private String localDownloadPath = System.getProperty("java.io.tmpdir");  
  30.     private String localDownloadPath = "E:\\素材\\pictures\\downloads\\";  
  31.     private boolean followRedirects = true;  
  32.     private boolean mimicWebDriverCookieState = true;  
  33.     private int httpStatusOfLastDownloadAttempt = 0;  
  34.    
  35.     public FileDownloader(WebDriver driverObject) {  
  36.         this.driver = driverObject;  
  37.     }  
  38.    
  39.     /** 
  40.      * Specify if the FileDownloader class should follow redirects when trying to download a file 
  41.      * 
  42.      * @param value 
  43.      */  
  44.     public void followRedirectsWhenDownloading(boolean value) {  
  45.         this.followRedirects = value;  
  46.     }  
  47.    
  48.     /** 
  49.      * Get the current location that files will be downloaded to. 
  50.      * 
  51.      * @return The filepath that the file will be downloaded to. 
  52.      */  
  53.     public String localDownloadPath() {  
  54.         return this.localDownloadPath;  
  55.     }  
  56.    
  57.     /** 
  58.      * Set the path that files will be downloaded to. 
  59.      * 
  60.      * @param filePath The filepath that the file will be downloaded to. 
  61.      */  
  62.     public void localDownloadPath(String filePath) {  
  63.         this.localDownloadPath = filePath;  
  64.     }  
  65.    
  66.     /** 
  67.      * Download the file specified in the href attribute of a WebElement 
  68.      * 
  69.      * @param element 
  70.      * @return 
  71.      * @throws Exception 
  72.      */  
  73.     public String downloadFile(WebElement element) throws Exception {  
  74.         return downloader(element, "href");  
  75.     }  
  76.    
  77.     /** 
  78.      * Download the image specified in the src attribute of a WebElement 
  79.      * 
  80.      * @param element 
  81.      * @return 
  82.      * @throws Exception 
  83.      */  
  84.     public String downloadImage(WebElement element) throws Exception {  
  85.         return downloader(element, "src");  
  86.     }  
  87.    
  88.     /** 
  89.      * Gets the HTTP status code of the last download file attempt 
  90.      * 
  91.      * @return 
  92.      */  
  93.     public int getHTTPStatusOfLastDownloadAttempt() {  
  94.         return this.httpStatusOfLastDownloadAttempt;  
  95.     }  
  96.    
  97.     /** 
  98.      * Mimic the cookie state of WebDriver (Defaults to true) 
  99.      * This will enable you to access files that are only available when logged in. 
  100.      * If set to false the connection will be made as an anonymouse user 
  101.      * 
  102.      * @param value 
  103.      */  
  104.     public void mimicWebDriverCookieState(boolean value) {  
  105.         this.mimicWebDriverCookieState = value;  
  106.     }  
  107.    
  108.     /** 
  109.      * Load in all the cookies WebDriver currently knows about so that we can mimic the browser cookie state 
  110.      * 
  111.      * @param seleniumCookieSet 
  112.      * @return 
  113.      */  
  114.     private BasicCookieStore mimicCookieState(Set<Cookie> seleniumCookieSet) {  
  115.         BasicCookieStore mimicWebDriverCookieStore = new BasicCookieStore();  
  116.         for (Cookie seleniumCookie : seleniumCookieSet) {  
  117.             BasicClientCookie duplicateCookie = new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue());  
  118.             duplicateCookie.setDomain(seleniumCookie.getDomain());  
  119.             duplicateCookie.setSecure(seleniumCookie.isSecure());  
  120.             duplicateCookie.setExpiryDate(seleniumCookie.getExpiry());  
  121.             duplicateCookie.setPath(seleniumCookie.getPath());  
  122.             mimicWebDriverCookieStore.addCookie(duplicateCookie);  
  123.         }  
  124.    
  125.         return mimicWebDriverCookieStore;  
  126.     }  
  127.    
  128.     /** 
  129.      * Perform the file/image download. 
  130.      * 
  131.      * @param element 
  132.      * @param attribute 
  133.      * @return 
  134.      * @throws IOException 
  135.      * @throws NullPointerException 
  136.      */  
  137.     private String downloader(WebElement element, String attribute) throws IOException, NullPointerException, URISyntaxException {  
  138.         String fileToDownloadLocation = element.getAttribute(attribute);  
  139.         MyLog.logger.info("attribute: "+fileToDownloadLocation);  
  140.         if (fileToDownloadLocation.trim().equals("")) throw new NullPointerException("The element you have specified does not link to anything!");  
  141.    
  142.         URL fileToDownload = new URL(fileToDownloadLocation);  
  143.         MyLog.logger.info("file: "+fileToDownload.getFile());  
  144.         File downloadedFile = new File(this.localDownloadPath + fileToDownload.getFile().replaceFirst("(/|\\\\).*(/|\\\\)"""));  
  145.         if (downloadedFile.canWrite() == false) downloadedFile.setWritable(true);  
  146.    
  147.         HttpClient client = new DefaultHttpClient();  
  148.         BasicHttpContext localContext = new BasicHttpContext();  
  149.    
  150.         MyLog.logger.info("Mimic WebDriver cookie state: " + this.mimicWebDriverCookieState);  
  151.         if (this.mimicWebDriverCookieState) {  
  152.             localContext.setAttribute(ClientContext.COOKIE_STORE, mimicCookieState(this.driver.manage().getCookies()));  
  153.         }  
  154.    
  155.         HttpGet httpget = new HttpGet(fileToDownload.toURI());  
  156.         HttpParams httpRequestParameters = httpget.getParams();  
  157.         httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, this.followRedirects);  
  158.         httpget.setParams(httpRequestParameters);  
  159.    
  160.         MyLog.logger.info("Sending GET request for: " + httpget.getURI());  
  161.         HttpResponse response = client.execute(httpget, localContext);  
  162.         this.httpStatusOfLastDownloadAttempt = response.getStatusLine().getStatusCode();  
  163.         MyLog.logger.info("HTTP GET request status: " + this.httpStatusOfLastDownloadAttempt);  
  164.         if(this.httpStatusOfLastDownloadAttempt==200){  
  165.             MyLog.logger.info("Downloading file: " + downloadedFile.getName());  
  166.             FileUtils.copyInputStreamToFile(response.getEntity().getContent(), downloadedFile);  
  167.             response.getEntity().getContent().close();  
  168.        
  169.             String downloadedFileAbsolutePath = downloadedFile.getAbsolutePath();  
  170.             MyLog.logger.info("File downloaded to '" + downloadedFileAbsolutePath + "'");  
  171.        
  172.             return downloadedFileAbsolutePath;  
  173.         }  
  174.         return "";  
  175.           
  176.     }  
  177. }  

RequestMethod类

[java]  view plain  copy
  1. package com.test.filedownloader;  
  2.   
  3. import org.apache.http.client.methods.*;  
  4.   
  5. public enum RequestMethod {  
  6.     OPTIONS(new HttpOptions()),  
  7.     GET(new HttpGet()),  
  8.     HEAD(new HttpHead()),  
  9.     POST(new HttpPost()),  
  10.     PUT(new HttpPut()),  
  11.     DELETE(new HttpDelete()),  
  12.     TRACE(new HttpTrace());  
  13.   
  14.     private final HttpRequestBase requestMethod;  
  15.   
  16.     RequestMethod(HttpRequestBase requestMethod) {  
  17.         this.requestMethod = requestMethod;  
  18.     }  
  19.   
  20.     public HttpRequestBase getRequestMethod() {  
  21.         return this.requestMethod;  
  22.     }  
  23. }  

调用类部分代码:

[java]  view plain  copy
  1.     @Test  
  2.     public void DownloadImages() throws Exception{  
  3. //      BaiduImgDownload BaiduDownloadPics=new BaiduImgDownload();  
  4.           
  5.         wait=new WebDriverWait(driver,10);  
  6.         String testProject="scmtest";  
  7.         String testPlan="DownloadPicsfromBaidu";  
  8.         String testcase="download pictures from Baidu website";  
  9.         String build="DownloadPicsfromBaidu";  
  10.         String notes=null;  
  11.         String result=null;  
  12.         try{  
  13. //          driver.manage().window().maximize();  
  14.             FileDownloader fileDownloader=new FileDownloader(driver);  
  15.             driver.get(baseUrl +"search/detail?ct=503316480&z=0&ipn=false&word=头像 可爱&pn=8&spn=0&di=48693053420&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=&ie=utf-8&oe=utf-8&in=3354&cl=2&lm=-1%2C&st=&cs=2390703471%2C168602444&os=2076211555%2C1322829468&adpicid=0&ln=2000&fr=ala&fmq=1378374347070_R&ic=0&s=0%2C&se=&sme=&tab=&face=&ist=&jit=&statnum=head&cg=head&bdtype=0&objurl=http%3A%2F%2Fimg5.duitang.com%2Fuploads%2Fitem%2F201403%2F14%2F20140314121845_8iTiY.thumb.700_0.jpeg&fromurl=http%3A%2F%2Fwww.duitang.com%2Fpeople%2Fmblog%2F204985052%2Fdetail%2F&gsm=0");  
  16.             WebElement image=driver.findElement(By.cssSelector("div.img-wrapper>img"));  
  17.             int count=1;  
  18.             while(count<6){  
  19.                 boolean isVisible=this.IsImageVisible(driver, image);  
  20.                 if(isVisible){  
  21.                     String imgAbsoluteLocat=fileDownloader.downloadImage(image);  
  22.                     if(imgAbsoluteLocat!=""){  
  23.                         MyLog.logger.info("----"+count+" picture is available");  
  24.                         assertThat(new File(imgAbsoluteLocat).exists(),is(equalTo(true)));  
  25.                         assertThat(fileDownloader.getHTTPStatusOfLastDownloadAttempt(), is(equalTo(200)));  
  26.                     }else{  
  27.                         MyLog.logger.info("----"+count+" picture is unavailable");  
  28.                     }  
  29.                       
  30.                     driver.findElement(By.cssSelector("span.img-next > span.img-switch-btn")).click();  
  31.                     driver.switchTo().defaultContent();  
  32.                     MyLog.logger.info("----navigate to the next img");  
  33.                 }  
  34.                 count++;  
  35.             }  
  36. //              wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("h4[title='品牌']")));  
  37. //          assertNotNull("login name not found",driver.findElement(By.xpath("//h1[contains(text(),'Free Photos about valentine')]")));  
  38. //          driver.findElement(By.xpath("//h1[contains(text(),'Free Photos about valentine')]")).click();     
  39.               
  40. //              result=TestLinkAPIResults.TEST_PASSED;  
  41. //              notes="Automated Executed successfully by java at "+dateformat.format(new Date());  
  42. //              System.out.println("-success--");  
  43.             MyLog.logger.info("---bottom--");  
  44.           
  45.         }catch(Exception e){  
  46.             MyLog.logger.info("=fail 2==\n"+e.getMessage());  
  47.             result=TestLinkAPIResults.TEST_FAILED;  
  48.             notes="Automated Execution failed by java at "+dateformat.format(new Date());  
  49.         }catch(Error e){  
  50.             MyLog.logger.info("Error:"+e.getMessage());  
  51.         }finally{  
  52.             MyLog.logger.info("=00==");  
  53. //          automateLogin163.reportResult(testProject, testPlan, testcase, build, notes, result);  
  54. //          System.out.println("*have updated testlink testcase status**");  
  55.         }  
  56.     }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值