抓取服务器图片下载到本地

Sample code:

import org.apache.http.Header;

import org.apache.http.HttpResponse;

import org.apache.http.HttpStatus;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

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

import org.apache.http.impl.client.DefaultHttpClient;

public void download(String path, String url) {

//  String url = "xxxxxxxx";

//  String path = "F:/test.jpg";

HttpClient client = null;

try {

// 创建HttpClient对象

client = new DefaultHttpClient();

// 获得HttpGet对象

HttpGet httpGet = getHttpGet(url, null, null);

// 发送请求获得返回结果

HttpResponse response = client.execute(httpGet);

// 如果成功

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

byte[] result = EntityUtils.toByteArray(response.getEntity());

BufferedOutputStream bw = null;

try {

// 创建文件对象

File f = new File(path);

// 创建文件路径

if (!f.getParentFile().exists())

f.getParentFile().mkdirs();

// 写入文件

bw = new BufferedOutputStream(new FileOutputStream(path));

bw.write(result);

} catch (Exception e) {

log.error("保存文件错误,path=" + path + ",url=" + url, e);

} finally {

try {

if (bw != null)

bw.close();

} catch (Exception e) {

log.error(

"finally BufferedOutputStream shutdown close",

e);

}

}

}

// 如果失败

else {

StringBuffer errorMsg = new StringBuffer();

errorMsg.append("httpStatus:");

errorMsg.append(response.getStatusLine().getStatusCode());

errorMsg.append(response.getStatusLine().getReasonPhrase());

errorMsg.append(", Header: ");

Header[] headers = response.getAllHeaders();

for (Header header : headers) {

errorMsg.append(header.getName());

errorMsg.append(":");

errorMsg.append(header.getValue());

}

log.error("HttpResonse Error:" + errorMsg);

}

} catch (ClientProtocolException e) {

log.error("下载文件保存到本地,http连接异常,path=" + path + ",url=" + url, e);

} catch (IOException e) {

log.error("下载文件保存到本地,文件操作异常,path=" + path + ",url=" + url, e);

} finally {

try {

client.getConnectionManager().shutdown();

} catch (Exception e) {

log.error("finally HttpClient shutdown error", e);

}

}

}

private static HttpGet getHttpGet(String url, Map<String, String> params,

String encode) {

StringBuffer buf = new StringBuffer(url);

if (params != null) {

// 地址增加?或者&

String flag = (url.indexOf(‘?‘) == -1) ? "?" : "&";

// 添加参数

for (String name : params.keySet()) {

buf.append(flag);

buf.append(name);

buf.append("=");

try {

String param = params.get(name);

if (param == null) {

param = "";

}

buf.append(URLEncoder.encode(param, encode));

} catch (UnsupportedEncodingException e) {

log.error("URLEncoder Error,encode=" + encode + ",param="

+ params.get(name), e);

}

flag = "&";

}

}

HttpGet httpGet = new HttpGet(buf.toString());

return httpGet;

}

时间: 2024-08-28 21:02:43

抓取服务器图片下载到本地的相关文章

使用Puppeteer进行数据抓取(四)——图片下载

大多数情况下,图片获取并不是很困难的事情,获取图片的url,然后模拟浏览器请求即可.但是,有的时候这种方法往往无法生效,常见的情形有: 动态图片,每次获取都是一个新的,例如图片验证码,重新获取时是一个新的验证码图片,已经失去了效果了. 动态上下文,有的网站为了反爬虫,获取图片时要加上其动态生成的cookie才行. 这些情况下,使用puppeteer驱动chrome浏览器能看到图片,但获取url后单独请求时,要么获取到的图片无效,要么获取不到图片.本文这里就简单的介绍下一些十分通用且有效的下载这些

ASP.NET下载远程图片保存到本地的方法、保存抓取远程图片

ASP.NET下载远程图片保存到本地的方法.保存抓取远程图片 2012-05-16 11:25:51     我来说两句      收藏    我要投稿 以下介绍两种方法:1.利用WebRequest,WebResponse 类WebRequest wreq=WebRequest.Create("http://up.2cto.com/2012/0516/20120516112717995.gif");    HttpWebResponse wresp=(HttpWebResponse)

scrapy框架来爬取壁纸网站并将图片下载到本地文件中

首先需要确定要爬取的内容,所以第一步就应该是要确定要爬的字段: 首先去items中确定要爬的内容 class MeizhuoItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() # 图集的标题 title = scrapy.Field() # 图片的url,需要来进行图片的抓取 url = scrapy.Field() pass 在确定完要爬的字段之后,就是分析网站页面的请求

抓取远程图片到本地,你会用什么函数?

方式有: <?php $img = file_get_contents('http://www.xfcodes.com/ img/baidu_logo.gif'); file_put_contents('1.gif',$img); echo '<img src="1.gif">'; 这段抓取远程图片至本地在运行中360极速.火狐.谷歌没有出现错误,可以正常运行. 另外还有: <?php $pagecontent = file_get_contents('http

通过WebClient类来发起请求并下载html 抓取邮箱 图片

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Text.RegularExpressions; using System.IO; namespace 通过WebClient类来发起请求并下载html 抓取邮箱 图片 { class Program { static void Main(string[] args

Python爬虫抓取网页图片

本文通过python 来实现这样一个简单的爬虫功能,把我们想要的图片爬取到本地. 下面就看看如何使用python来实现这样一个功能. # -*- coding: utf-8 -*- import urllib import re import time import os #显示下载进度 def schedule(a,b,c): ''''' a:已经下载的数据块 b:数据块的大小 c:远程文件的大小 ''' per = 100.0 * a * b / c if per > 100 : per =

Python -- 网络编程 -- 抓取网页图片 -- 图虫网

字符串(str)编码成字节码(bytes),字节码解码为字符串 获取当前环境编码:sys.stdin.encoding url编码urllib.parse.quote() url解码urllib.parse.unquote() 列表去重:pages = list(set(pages)) 创建文件夹(可多级创建):os.makedirs(folder)  os.mkdir()只能单级创建 首先分析网页(图虫网)的URL规律: 根网页地址形如: http://tuchong.com/tags/人像/

Python3简单爬虫抓取网页图片

现在网上有很多python2写的爬虫抓取网页图片的实例,但不适用新手(新手都使用python3环境,不兼容python2),所以我用Python3的语法写了一个简单抓取网页图片的实例,希望能够帮助到大家,并希望大家批评指正. 1 import urllib.request 2 import re 3 import os 4 import urllib 5 #根据给定的网址来获取网页详细信息,得到的html就是网页的源代码 6 def getHtml(url): 7 page = urllib.r

百度UEditor编辑器关闭抓取远程图片功能(默认开启)

这个坑娘的功能,开始时居然不知道如何触发,以为有个按钮,点击一下触发,翻阅了文档,没有发现,然后再网络上看到原来是复制粘贴非白名单内的图片到编辑框时触发,坑娘啊............... 问题又来了:今天在写百度UEditor编辑器的[取远程图片功能]时有碰到:该功能如何关闭了? 又花了15分钟左右的时间查阅了[官方文档]以及[官方论坛],都没有找到解决办法,那就查阅下源文件看看,是否有相关的判断呢(本人JS非常烂) 于是马上查阅:ueditor.all.js文件,发现如下代码 // plu