Crawler学习:2.Download Pages

声明:所有内容均为本人学习《自己动手写网络爬虫》心得,有任何疑问可以参考原文。


1.网页抓取

所谓网页抓取,就是把URL 地址中指定的网络资源从网络流中读取出来,保存到本地。

类似于使用程序模拟IE 浏览器的功能,把URL 作为HTTP 请求的内容发送到服务器端,然后读取服务器端的响应资源。

Java 语言是为网络而生的编程语言,它把网络资源看成是一种文件,它对网络资源的访问和对本地文件的访问一样方便。它把请求和响应封装为流。

因此我们可以根据相应内容,获得响应流,之后从流中按字节读取数据。

例如,java.net.URL 类可以对相应的Web服务器发出请求并且获得响应文档。

java.net.URL 类有一个默认的构造函数,使用URL 地址作为参数,构造URL 对象:

URL pageURL = new URL(path);

接着,可以通过获得的URL 对象来取得网络流,进而像操作本地文件一样来操作网络资源:

InputStream stream = pageURL.openStream();

在实际的项目中,网络环境比较复杂,因此,只用java.net 包中的API 来模拟IE 客户端的工作,代码量非常大。

需要处理HTTP 返回的状态码,设置HTTP 代理,处理HTTPS协议等工作。

为了便于应用程序的开发,实际开发时常常使用Apache 的HTTP 客户端开源项目——HttpClient。

它完全能够处理HTTP 连接中的各种问题,使用起来非常方便。

只需在项目中引入HttpClient.jar(3.0版本) 包,就可以模拟IE 来获取网页内容。例如:

//创建一个客户端,类似于打开一个浏览器
HttpClient httpclient=new HttpClient();
//创建一个get 方法,类似于在浏览器地址栏中输入一个地址
GetMethod getMethod=new GetMethod("http://www.blablabla.com");
//回车,获得响应状态码
int statusCode=httpclient.executeMethod(getMethod);
//查看命中情况,可以获得的东西还有很多,比如head、cookies 等
System.out.println("response=" + getMethod.getResponseBodyAsString());
//释放
getMethod.releaseConnection();

2.传参数方法:Get和Post

Get 请求方式把需要传递给服务器的参数作为URL 的一部分传递给服务器。

但是,HTTP 协议本身对URL 字符串长度有所限制。因此不能传递过多的参数给服务器。

为了避免这种问题,通常情况下,采用Post 方法进行Http请求,HttpClient 包对post 方法也有很好的支持。例如:

/得到post 方法
PostMethod PostMethod = new PostMethod("http://www.saybot.com/postme");
//使用数组来传递参数
NameValuePair[] postData = new NameValuePair[2];
//设置参数
postData[0] = new NameValuePair("武器", "枪");
postData[1] = new NameValuePair("什么枪", "神枪");
postMethod.addParameters(postData);
//回车,获得响应状态码
int statusCode=httpclient.executeMethod(getMethod);
//查看命中情况,可以获得的东西还有很多,比如head、cookies 等
System.out.println("response=" + getMethod.getResponseBodyAsString());
//释放
getMethod.releaseConnection();
上面的例子说明了如何使用post 方法来访问Web 资源。与Get 方法不同,Post 方法可以使用NameValuePair 来设置参数,因此可以设置“无限”多的参数。


3.处理Http状态码

HttpClient 访问Web 资源的时候,涉及Http状态码。比如:

int statusCode=httpClient.executeMethod(getMethod);//回车,获得响应状态码

Http 状态码表示Http协议所返回的响应的状态。

比如客户端向服务器发送请求,如果成功地获得请求的资源,则返回的状态码为200,表示响应成功。

如果请求的资源不存在,则通常返回404 错误。


这里只简单处理了状态码为200的响应,其他状态码则都丢弃。

// 判断访问的状态码
if ( statusCode != HttpStatus.SC_OK ) {
    System.err.println("Method failed: " + getMethod.getStatusLine());
    filePath = null;
}

4.实现Download Pages

主要包含三个函数:

1.String getFileNameByUrl(String url,String contentType);  // 过滤URL中的非法字符,得到保存文件名。

2. void saveToLocal(byte[] data, String filePath);                    // 保存网络字节数组到本地文件。

3.String downloadFile(String url);                                              // 下载URL指向的网页。


package chici.util;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class DownloadFile {
	/**
	 * 根据URL和网页类型生成需要保存的网页的文件名,去除URL中的非文件名字符
	 * */
	public String getFileNameByUrl(String url,String contentType){
		// 移除http
		url = url.substring(7);
		// text/html类型
		if( contentType.indexOf("html")!=-1 ){
			return url.replaceAll("[\\?/:*|<>\"]","_") +".html";
		}
		// 如application/pdf类型
		else{
			return url.replaceAll("[\\?/:*|<>\"]","_") +"."+
					contentType.substring(contentType.lastIndexOf("/")+1);		
		}
	}
	
	/**
	 *保存网页字节数组到本地文件,filePath为要保存的文件的相对地址
	 * */
	private void saveToLocal(byte[] data, String filePath) {
		try {
			DataOutputStream out = new DataOutputStream( new FileOutputStream( new File(filePath) ) );
			
			for (int i = 0; i < data.length; i++)
				out.write(data[i]);
			
			out.flush();
			out.close();
		} catch (IOException e) {
				e.printStackTrace();
		}
	} 
	
	/**
	 * 下载URL指向的网页
	 * */
	public String downloadFile(String url) {
		String filePath = null;
		// 1.生成HttpClient 对象并设置参数
		HttpClient httpClient = new HttpClient();
		// 设置HTTP 连接超时5s
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
		
		// 2.生成GetMethod 对象并设置参数
		GetMethod getMethod = new GetMethod(url);
		// 设置get 请求超时5s
		getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,5000);
		// 设置请求重试处理
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
	
		// 3.执行HTTP GET 请求
		try {
			int statusCode = httpClient.executeMethod(getMethod);
			// 判断访问的状态码
			if ( statusCode != HttpStatus.SC_OK ) {
				System.err.println("Method failed: " + getMethod.getStatusLine());
				filePath = null;
			}
			
			// 4.处理HTTP 响应内容
			byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组
			// 根据网页url 生成保存时的文件名
			filePath = "E:\\chici\\"+ getFileNameByUrl(url, getMethod.getResponseHeader("Content-Type").getValue());
			saveToLocal(responseBody, filePath);
		} catch (HttpException e) {
			// 发生致命的异常,可能是协议不对或者返回的内容有问题
			System.out.println("Please check your provided http address!");
			e.printStackTrace();
		} catch (IOException e) {
			// 发生网络异常
			e.printStackTrace();
		} finally {
			// 释放连接
			getMethod.releaseConnection();
		}
		return filePath;
	}
		
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值