用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类

package com.test.filedownloader;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
 

import com.test.MyLog;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Set;

public class FileDownloader {
    private WebDriver driver;
//    private String localDownloadPath = System.getProperty("java.io.tmpdir");
    private String localDownloadPath = "E:\\素材\\pictures\\downloads\\";
    private boolean followRedirects = true;
    private boolean mimicWebDriverCookieState = true;
    private int httpStatusOfLastDownloadAttempt = 0;
 
    public FileDownloader(WebDriver driverObject) {
        this.driver = driverObject;
    }
 
    /**
     * Specify if the FileDownloader class should follow redirects when trying to download a file
     *
     * @param value
     */
    public void followRedirectsWhenDownloading(boolean value) {
        this.followRedirects = value;
    }
 
    /**
     * Get the current location that files will be downloaded to.
     *
     * @return The filepath that the file will be downloaded to.
     */
    public String localDownloadPath() {
        return this.localDownloadPath;
    }
 
    /**
     * Set the path that files will be downloaded to.
     *
     * @param filePath The filepath that the file will be downloaded to.
     */
    public void localDownloadPath(String filePath) {
        this.localDownloadPath = filePath;
    }
 
    /**
     * Download the file specified in the href attribute of a WebElement
     *
     * @param element
     * @return
     * @throws Exception
     */
    public String downloadFile(WebElement element) throws Exception {
        return downloader(element, "href");
    }
 
    /**
     * Download the image specified in the src attribute of a WebElement
     *
     * @param element
     * @return
     * @throws Exception
     */
    public String downloadImage(WebElement element) throws Exception {
        return downloader(element, "src");
    }
 
    /**
     * Gets the HTTP status code of the last download file attempt
     *
     * @return
     */
    public int getHTTPStatusOfLastDownloadAttempt() {
        return this.httpStatusOfLastDownloadAttempt;
    }
 
    /**
     * Mimic the cookie state of WebDriver (Defaults to true)
     * This will enable you to access files that are only available when logged in.
     * If set to false the connection will be made as an anonymouse user
     *
     * @param value
     */
    public void mimicWebDriverCookieState(boolean value) {
        this.mimicWebDriverCookieState = value;
    }
 
    /**
     * Load in all the cookies WebDriver currently knows about so that we can mimic the browser cookie state
     *
     * @param seleniumCookieSet
     * @return
     */
    private BasicCookieStore mimicCookieState(Set<Cookie> seleniumCookieSet) {
        BasicCookieStore mimicWebDriverCookieStore = new BasicCookieStore();
        for (Cookie seleniumCookie : seleniumCookieSet) {
            BasicClientCookie duplicateCookie = new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue());
            duplicateCookie.setDomain(seleniumCookie.getDomain());
            duplicateCookie.setSecure(seleniumCookie.isSecure());
            duplicateCookie.setExpiryDate(seleniumCookie.getExpiry());
            duplicateCookie.setPath(seleniumCookie.getPath());
            mimicWebDriverCookieStore.addCookie(duplicateCookie);
        }
 
        return mimicWebDriverCookieStore;
    }
 
    /**
     * Perform the file/image download.
     *
     * @param element
     * @param attribute
     * @return
     * @throws IOException
     * @throws NullPointerException
     */
    private String downloader(WebElement element, String attribute) throws IOException, NullPointerException, URISyntaxException {
        String fileToDownloadLocation = element.getAttribute(attribute);
        MyLog.logger.info("attribute: "+fileToDownloadLocation);
        if (fileToDownloadLocation.trim().equals("")) throw new NullPointerException("The element you have specified does not link to anything!");
 
        URL fileToDownload = new URL(fileToDownloadLocation);
        MyLog.logger.info("file: "+fileToDownload.getFile());
        File downloadedFile = new File(this.localDownloadPath + fileToDownload.getFile().replaceFirst("(/|\\\\).*(/|\\\\)", ""));
        if (downloadedFile.canWrite() == false) downloadedFile.setWritable(true);
 
        HttpClient client = new DefaultHttpClient();
        BasicHttpContext localContext = new BasicHttpContext();
 
        MyLog.logger.info("Mimic WebDriver cookie state: " + this.mimicWebDriverCookieState);
        if (this.mimicWebDriverCookieState) {
            localContext.setAttribute(ClientContext.COOKIE_STORE, mimicCookieState(this.driver.manage().getCookies()));
        }
 
        HttpGet httpget = new HttpGet(fileToDownload.toURI());
        HttpParams httpRequestParameters = httpget.getParams();
        httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, this.followRedirects);
        httpget.setParams(httpRequestParameters);
 
        MyLog.logger.info("Sending GET request for: " + httpget.getURI());
        HttpResponse response = client.execute(httpget, localContext);
        this.httpStatusOfLastDownloadAttempt = response.getStatusLine().getStatusCode();
        MyLog.logger.info("HTTP GET request status: " + this.httpStatusOfLastDownloadAttempt);
        if(this.httpStatusOfLastDownloadAttempt==200){
        	MyLog.logger.info("Downloading file: " + downloadedFile.getName());
            FileUtils.copyInputStreamToFile(response.getEntity().getContent(), downloadedFile);
            response.getEntity().getContent().close();
     
            String downloadedFileAbsolutePath = downloadedFile.getAbsolutePath();
            MyLog.logger.info("File downloaded to '" + downloadedFileAbsolutePath + "'");
     
            return downloadedFileAbsolutePath;
        }
        return "";
        
    }
}

RequestMethod类

package com.test.filedownloader;

import org.apache.http.client.methods.*;

public enum RequestMethod {
    OPTIONS(new HttpOptions()),
    GET(new HttpGet()),
    HEAD(new HttpHead()),
    POST(new HttpPost()),
    PUT(new HttpPut()),
    DELETE(new HttpDelete()),
    TRACE(new HttpTrace());

    private final HttpRequestBase requestMethod;

    RequestMethod(HttpRequestBase requestMethod) {
        this.requestMethod = requestMethod;
    }

    public HttpRequestBase getRequestMethod() {
        return this.requestMethod;
    }
}

调用类部分代码:

	@Test
	public void DownloadImages() throws Exception{
//		BaiduImgDownload BaiduDownloadPics=new BaiduImgDownload();
		
		wait=new WebDriverWait(driver,10);
		String testProject="scmtest";
		String testPlan="DownloadPicsfromBaidu";
		String testcase="download pictures from Baidu website";
		String build="DownloadPicsfromBaidu";
		String notes=null;
		String result=null;
		try{
//			driver.manage().window().maximize();
			FileDownloader fileDownloader=new FileDownloader(driver);
			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");
			WebElement image=driver.findElement(By.cssSelector("div.img-wrapper>img"));
			int count=1;
			while(count<6){
				boolean isVisible=this.IsImageVisible(driver, image);
				if(isVisible){
					String imgAbsoluteLocat=fileDownloader.downloadImage(image);
					if(imgAbsoluteLocat!=""){
						MyLog.logger.info("----"+count+" picture is available");
						assertThat(new File(imgAbsoluteLocat).exists(),is(equalTo(true)));
						assertThat(fileDownloader.getHTTPStatusOfLastDownloadAttempt(), is(equalTo(200)));
					}else{
						MyLog.logger.info("----"+count+" picture is unavailable");
					}
					
					driver.findElement(By.cssSelector("span.img-next > span.img-switch-btn")).click();
					driver.switchTo().defaultContent();
					MyLog.logger.info("----navigate to the next img");
				}
				count++;
			}
//				wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("h4[title='品牌']")));
//			assertNotNull("login name not found",driver.findElement(By.xpath("//h1[contains(text(),'Free Photos about valentine')]")));
//			driver.findElement(By.xpath("//h1[contains(text(),'Free Photos about valentine')]")).click();	
			
//				result=TestLinkAPIResults.TEST_PASSED;
//				notes="Automated Executed successfully by java at "+dateformat.format(new Date());
//				System.out.println("-success--");
			MyLog.logger.info("---bottom--");
		
		}catch(Exception e){
			MyLog.logger.info("=fail 2==\n"+e.getMessage());
			result=TestLinkAPIResults.TEST_FAILED;
			notes="Automated Execution failed by java at "+dateformat.format(new Date());
		}catch(Error e){
			MyLog.logger.info("Error:"+e.getMessage());
		}finally{
			MyLog.logger.info("=00==");
//			automateLogin163.reportResult(testProject, testPlan, testcase, build, notes, result);
//			System.out.println("*have updated testlink testcase status**");
		}
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值