java简单实现网络爬虫

来源:互联网 发布:盐城平面设计软件培训 编辑:程序博客网 时间:2024/04/28 09:35

本文为收集网络资源,为大家整理好了一篇较为简单的java网络爬虫,亲测可用。

需要的jar包:commons-httpclient.jar,commons-codec.jar,commons-logging.jar直接百度就可以下载

给出链接:http://dl.download.csdn.net/down10/20140701/4c501983ebd07c9b89b8c247b823633b.rar?response-content-disposition=attachment%3Bfilename%3D%22jar%E5%8C%85.rar%22&OSSAccessKeyId=9q6nvzoJGowBj4q1&Expires=1459762725&Signature=SEgWZzOTb8PBXMfkIMBrZEbtmzk%3D

需要jar包:http://218.58.222.83/ws.cdn.baidupcs.com/file/6982cbda7b03e016f789378ecdc51e90?bkt=p2-nj-523&xcode=a38e85174a0238cd75379b889806913f0540f73fa84a6d5ced03e924080ece4b&fid=3946663331-250528-42244034374853&time=1459748428&sign=FDTAXGERLBH-DCb740ccc5511e5e8fedcff06b081203-2fM3f6wLrLUwqn9mKXopw79aTYA%3D&to=lc&fm=Nin,B,U,nc&sta_dx=0&sta_cs=71&sta_ft=zip&sta_ct=7&fm2=Ningbo,B,U,nc&newver=1&newfm=1&secfm=1&flow_ver=3&pkey=14006982cbda7b03e016f789378ecdc51e907172f4e6000000050e2a&sl=78643279&expires=8h&rt=sh&r=157126347&mlogid=2193340102490911147&vuk=2722565501&vbdid=2865948595&fin=HTMLParser-2.0-SNAPSHOT-bin.zip&fn=HTMLParser-2.0-SNAPSHOT-bin.zip&slt=pm&uta=0&rtype=1&iv=0&isw=0&dp-logid=2193340102490911147&dp-callid=0.1.1&wshc_tag=0&wsts_tag=5701fe4f&wsid_tag=70c3958d&wsiphost=ipdbm

然后把jar包放到java项目的lib文件,没有新建,然后选择项目右键构建编译路径,把这些包加进去,则环境配置完成。


代码如下:

package netpc;



import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.Queue;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import netpc.netpacl.LinkFilter;
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;
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;
import java.util.Set;














public class netpacl {


private void initCrawlerWithSeeds(String[] seeds) {
 for (int i = 0; i < seeds.length; i++)
  LinkQueue.addUnvisitedUrl(seeds[i]);
}




public void crawling(String[] seeds) { // 定义过滤器,提取以http://www.lietu.com开头的链接
 LinkFilter filter = new LinkFilter() {
  public boolean accept(String url) {
   if (url.startsWith("http://tech.diannaodian.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);
  }
 }
}
public interface LinkFilter {  
    public boolean accept(String url);
}  




// main 方法入口
public static void main(String[] args) {
netpacl crawler = new netpacl();
 crawler.crawling(new String[] { "http://tech.diannaodian.com/oa/bj/qb/2016/0403/367161.html" });
}


}














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;
}
}












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 = "H:\\H\\"
    + 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;
}
}










 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();
}


}


结果:在代码中上述你选择的路径下保存html文件

注意:url.startsWith("http://tech.diannaodian.com")

 crawler.crawling(new String[] { "http://tech.diannaodian.com/oa/bj/qb/2016/0403/367161.html" 区别,后者为你访问的首次具体网页,前者为过滤网页。


 
0 0