网络爬虫简介与实现

最近在做一个网站,需要很多测试的数据,比如图书的图片或者文本内容,人工找下载图片和内容太慢,于是准备用代码实现,网上一查,发现网络爬虫特别好用,于是便学习了怎么实现,发现真的很好用。下面给个源码简单实现获取新浪首页的网络爬虫。

/**
 * 
 * @author Benett
 * 
 */
public class Spider {
	private static HttpClient httpClient = new HttpClient();

	/**
	 * @param path
	 *            目标网页的链接
	 * @return 返回布尔值,表示是否正常下载目标页面
	 * @throws Exception
	 *             读取网页流或写入本地文件流的IO异常
	 */
	public static boolean downloadPage(String path) throws Exception {
		// 定义输入输出流
		InputStream input = null;
		OutputStream output = null;
		// 得到 post 方法
		GetMethod getMethod = new GetMethod(path);
		// 执行,返回状态码
		int statusCode = httpClient.executeMethod(getMethod);
		// 针对状态码进行处理
		// 简单起见,只处理返回值为 200 的状态码
		if (statusCode == HttpStatus.SC_OK) {
			input = getMethod.getResponseBodyAsStream();
			// 通过对URL的得到文件名
			String filename = path.substring(path.lastIndexOf('/') + 1)
					+ ".html";
			// 获得文件输出流
			output = new FileOutputStream(filename);
			// 输出到文件
			int tempByte = -1;
			while ((tempByte = input.read()) > 0) {
				output.write(tempByte);
			}
			// 关闭输入流
			if (input != null) {
				input.close();
			}
			// 关闭输出流
			if (output != null) {
				output.close();
			}
			return true;
		}
		return false;
	}

	public static void main(String[] args) {
		try {
			// 抓取新浪首页,输出
			Spider.downloadPage("http://www.sina.com.cn");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
结果:


下面实现一个难一点的,实现抓取所有以www.baidu.com开头的网页,有4个类和一个测试类

DownLoadFile类:

package webspider;

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;

/**
 * 2.定义DownLoadFile类,根据得到的url,爬取网页内容,下载到本地保存。
 * @author Benett
 *
 */
public class DownLoadFile {
	/**
	 * 根据 url 和网页类型生成需要保存的网页的文件名 去除掉 url 中非文件名字符
	 */
	public String getFileNameByUrl(String url, String contentType) {
		// remove http://
		url = url.substring(7);
		// text/html类型
		if (contentType.indexOf("html") != -1) {
			url = url.replaceAll("[\\?/:*|<>\"]", "_") + ".html";
			return url;
		}
		// 如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.生成 HttpClinet 对象并设置参数 */
		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 = "f:\\spider\\"
					+ 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;
	}
}

HtmlParserTool类

package webspider;

import java.util.HashSet;
import java.util.Set;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

/**
 *3. 定义HtmlParserTool类,用来获得网页中的超链接(包括a标签,frame中的src等等),即为了得到子节点的URL。
 * @author Benett
 *
 */
public class HtmlParserTool {
	// 获取一个网站上的链接,filter 用来过滤链接
	public static Set<String> extracLinks(String url, LinkFilter filter) {
		Set<String> links = new HashSet<String>();
		try {
			Parser parser = new Parser(url);
			// parser.setEncoding("utf-8");
			// 过滤 <frame >标签的 filter,用来提取 frame 标签里的 src 属性所表示的链接
			NodeFilter frameFilter = new NodeFilter() {
				public boolean accept(Node node) {
					if (node.getText().startsWith("frame src=")) {
						return true;
					} else {
						return false;
					}
				}
			};
			// OrFilter 来设置过滤 <a> 标签,和 <frame> 标签
			OrFilter linkFilter = new OrFilter(new NodeClassFilter(
					LinkTag.class), frameFilter);
			// 得到所有经过过滤的标签
			NodeList list = parser.extractAllNodesThatMatch(linkFilter);
			for (int i = 0; i < list.size(); i++) {
				Node tag = list.elementAt(i);
				if (tag instanceof LinkTag)// <a> 标签
				{
					LinkTag link = (LinkTag) tag;
					String linkUrl = link.getLink();// url
					if (filter.accept(linkUrl))
						links.add(linkUrl);
				} else// <frame> 标签
				{
					// 提取 frame 里 src 属性的链接如 <frame src="test.html"/>
					String frame = tag.getText();
					int start = frame.indexOf("src=");
					frame = frame.substring(start);
					int end = frame.indexOf(" ");
					if (end == -1)
						end = frame.indexOf(">");
					String frameUrl = frame.substring(5, end - 1);
					if (filter.accept(frameUrl))
						links.add(frameUrl);
				}
			}
		} catch (ParserException e) {
			e.printStackTrace();
		}
		return links;
	}
}

LinkFilter类

package webspider;

public interface LinkFilter {
	public boolean accept(String url);
}

LinkQueue类

package webspider;

import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.Queue;

/**
 * 1.定义已访问队列,待访问队列和爬取得URL的哈希表,包括出队列,入队列,判断队列是否空等操作
 * @author Benett
 *
 */
public class LinkQueue {
	// 已访问的 url 集合
	private static Set visitedUrl = new HashSet();
	// 待访问的 url 集合
	private static Queue unVisitedUrl = new PriorityQueue();

	// 获得URL队列
	public static Queue getUnVisitedUrl() {
		return unVisitedUrl;
	}

	// 添加到访问过的URL队列中
	public static void addVisitedUrl(String url) {
		visitedUrl.add(url);
	}

	// 移除访问过的URL
	public static void removeVisitedUrl(String url) {
		visitedUrl.remove(url);
	}

	// 未访问的URL出队列
	public static Object unVisitedUrlDeQueue() {
		return unVisitedUrl.poll();
	}

	// 保证每个 url 只被访问一次
	public static void addUnvisitedUrl(String url) {
		if (url != null && !url.trim().equals("") && !visitedUrl.contains(url)
				&& !unVisitedUrl.contains(url))
			unVisitedUrl.add(url);
	}

	// 获得已经访问的URL数目
	public static int getVisitedUrlNum() {
		return visitedUrl.size();
	}

	// 判断未访问的URL队列中是否为空
	public static boolean unVisitedUrlsEmpty() {
		return unVisitedUrl.isEmpty();
	}
}
测试类:

package webspider;
import java.util.Set;

/**
 * 4.编写测试类MyCrawler,用来测试爬取效果
 * @author Benett
 *
 */
public class MyCrawler {
 /**
  * 使用种子初始化 URL 队列
  * 
  * @return
  * @param seeds
  *            种子URL
  */
 private void initCrawlerWithSeeds(String[] seeds) {
  for (int i = 0; i < seeds.length; i++)
   LinkQueue.addUnvisitedUrl(seeds[i]);
 }
 /**
  * 抓取过程
  * 
  * @return
  * @param seeds
  */
 public void crawling(String[] seeds) { // 定义过滤器,提取以http://www.lietu.com开头的链接
  LinkFilter filter = new LinkFilter() {
   public boolean accept(String url) {
    if (url.startsWith("http://www.baidu.com"))
     return true;
    else
     return false;
   }
  };
  // 初始化 URL 队列
  initCrawlerWithSeeds(seeds);
  // 循环条件:待抓取的链接不空且抓取的网页不多于1000
  while (!LinkQueue.unVisitedUrlsEmpty()
    && LinkQueue.getVisitedUrlNum() <= 1000) {
   // 队头URL出队列
   String visitUrl = (String) LinkQueue.unVisitedUrlDeQueue();
   if (visitUrl == null)
    continue;
   DownLoadFile downLoader = new DownLoadFile();
   // 下载网页
   downLoader.downloadFile(visitUrl);
   // 该 url 放入到已访问的 URL 中
   LinkQueue.addVisitedUrl(visitUrl);
   // 提取出下载网页中的 URL
   Set<String> links = HtmlParserTool.extracLinks(visitUrl, filter);
   // 新的未访问的 URL 入队
   for (String link : links) {
    LinkQueue.addUnvisitedUrl(link);
   }
  }
 }
 // main 方法入口
 public static void main(String[] args) {
  MyCrawler crawler = new MyCrawler();
  crawler.crawling(new String[] { "http://www.baidu.com" });
 }

案例结果:


该案例相关jar包下载链接:

http://download.csdn.net/detail/sky_100/9737799






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值