import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// 搜索Web爬行者
public class SearchCrawler implements Runnable {
/*
* disallowListCache缓存robot不允许搜索的URL。 Robot协议在Web站点的根目录下设置一个robots.txt文件,
* 规定站点上的哪些页面是限制搜索的。 搜索程序应该在搜索过程中跳过这些区域,下面是robots.txt的一个例子: # robots.txt for
* http://somehost.com/ User-agent: Disallow: /cgi-bin/ Disallow:
* /registration # Disallow robots on registration page Disallow: /login
*/
HashSet<urlclass> crawledList = new HashSet<urlclass>();
LinkedHashSet<urlclass> toCrawlList = new LinkedHashSet<urlclass>();
static int level=0;
PrintWriter pw = null;
private HashMap<String, ArrayList<String>> disallowListCache = new HashMap<String, ArrayList<String>>();
ArrayList<String> errorList = new ArrayList<String>();// 错误信息
ArrayList<String> robotsAllowed = new ArrayList<String>();// AllowedURL
String startUrl;// 开始搜索的起点
int maxUrl;// 最大处理的url数
String searchString;// 要搜索的字符串(英文)
boolean caseSensitive = false;// 是否区分大小写
boolean limitHost = true;// 是否在限制的主机内搜索
public SearchCrawler(String startUrl, int maxUrl, String searchString) {
this.startUrl = startUrl;
this.maxUrl = maxUrl;
this.searchString = searchString;
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter(
"d:\\out.txt")));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {// 启动搜索线程
crawl(startUrl, maxUrl, searchString, limitHost, caseSensitive);
pw.flush();
pw.close();
}
// 检测URL格式
private URL verifyUrl(String url) {
// 只处理HTTP URLs.
if (!url.toLowerCase().startsWith("http://"))
return null;
URL verifiedUrl = null;
try {
verifiedUrl = new URL(url);
} catch (Exception e) {
return null;
}
return verifiedUrl;
}
// 检测robot是否允许访问给出的URL.
private boolean isRobotAllowed(URL urlToCheck) {
// private boolean getRobotAllowed(URL urlToCheck) {
String host = urlToCheck.getHost().toLowerCase();// 获取给出RUL的主机
// System.out.println("主机=" + host);
// 获取主机不允许搜索的URL缓存
ArrayList<String> disallowList = disallowListCache.get(host);
// 如果还没有缓存,下载并缓存。
if (disallowList == null) {
// System.out.println("几次?");
disallowList = new ArrayList<String>();
try {
URL robotsFileUrl = new URL("http://" + host + "/robots.txt");
BufferedReader reader = new BufferedReader(
new InputStreamReader(robotsFileUrl.openStream()));
// 读robot文件,创建不允许访问的路径列表。
String line;
while ((line = reader.readLine()) != null) {
if (line.indexOf("Disallow:") == 0) {// 是否包含"Disallow:"
String disallowPath = line.substring("Disallow:"
.length());// 获取不允许访问路径
// 检查是否有注释。
int commentIndex = disallowPath.indexOf("#");
if (commentIndex != -1) {
disallowPath = disallowPath.substring(0,
commentIndex);// 去掉注释
}
disallowPath = disallowPath.trim();
disallowList.add(disallowPath);
}
}
// 缓存此主机不允许访问的路径。
disallowListCache.put(host, disallowList);
} catch (Exception e) {
return true; // web站点根目录下没有robots.txt文件,返回真
}
}
String file = urlToCheck.getFile();
// System.out.println("文件getFile()="+file);
for (int i = 0; i < disallowList.size(); i++) {
String disallow = disallowList.get(i);
if (file.startsWith(disallow)) {
return false;
}
}
return true;
}
private String downloadPage(URL pageUrl) {
try {
// Open connection to URL for reading.
BufferedReader reader = new BufferedReader(new InputStreamReader(
pageUrl.openStream(), "utf-8"));
// Read page into buffer.
String line;
StringBuffer pageBuffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
pageBuffer.append(line);
}
return pageBuffer.toString();
} catch (Exception e) {
}
return null;
}
// 从URL中去掉"www"
private String removeWwwFromUrl(String url) {
int index = url.indexOf("://www.");
if (index != -1) {
return url.substring(0, index + 3) + url.substring(index + 7);
}
return (url);
}
// 解析页面并找出链接
private ArrayList<urlclass> retrieveLinks(URL pageUrl, String pageContents,
boolean limitHost, int depth) {
// 用正则表达式编译链接的匹配模式。
Pattern p = Pattern.compile("<a\\s+href\\s*=\\s*\"?(.*?)[\"|>]",
Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(pageContents);
ArrayList<urlclass> linkList = new ArrayList<urlclass>();
while (m.find()) {
String link = m.group(1).trim();
if (link.length() < 1) {
continue;
}
// 跳过链到本页面内链接。
if (link.charAt(0) == '#') {
continue;
}
if (link.indexOf("mailto:") != -1) {
continue;
}
if (link.toLowerCase().indexOf("javascript") != -1) {
continue;
}
int port = pageUrl.getPort();
if (port == -1)
port = 80;
if (link.indexOf("://") == -1) {
if (link.charAt(0) == '/') {// 处理绝对地址
link = "http://" + pageUrl.getHost() + ":" + port + link;
} else {
String file = pageUrl.getFile();
if (file.indexOf('/') == -1) {// 处理相对地址
link = "http://" + pageUrl.getHost() + ":" + port + "/"
+ link;
} else {
String path = file.substring(0,
file.lastIndexOf('/') + 1);
link = "http://" + pageUrl.getHost() + ":" + port
+ path + link;
}
}
}
int index = link.indexOf('#');
if (index != -1) {
link = link.substring(0, index);
}
link = removeWwwFromUrl(link).trim();
URL verifiedLink = verifyUrl(link);
if (verifiedLink == null) {
continue;
}
/* 如果限定主机,排除那些不合条件的URL */
if (limitHost
&& !pageUrl.getHost().toLowerCase()
.equals(verifiedLink.getHost().toLowerCase())) {
continue;
}
urlclass u = new urlclass(link, depth + 1);
// 跳过那些已经处理的链接.
if (crawledList.contains(u)) {
continue;
} else {
linkList.add(u);
// pw1.println("add to tocrawler: "+u.toString());
}
}
return linkList;
}
// 搜索下载Web页面的内容,判断在该页面内有没有指定的搜索字符串
private boolean searchStringMatches(String pageContents,
String searchString, boolean caseSensitive) {
String searchContents = pageContents;
if (!caseSensitive) {// 如果不区分大小写
searchContents = pageContents.toLowerCase();
}
System.out.println(searchContents);
Pattern p = Pattern.compile("[\\s]+");
String[] terms = p.split(searchString);
for (int i = 0; i < terms.length; i++) {
System.out.println("terms[i]:" + terms[i]);
if (caseSensitive) {
if (searchContents.indexOf(terms[i]) == -1) {
return false;
}
} else {
if (searchContents.indexOf(terms[i].toLowerCase()) == -1) {
return false;
}
}
}
return true;
}
// 执行实际的搜索操作
@SuppressWarnings("unused")
public ArrayList<String> crawl(String startUrl, int maxUrls,
String searchString, boolean limithost, boolean caseSensitive) {
if (maxUrls < 1) {
errorList.add("Invalid Max URLs value.");
System.out.println("Invalid Max URLs value.");
}
if (searchString.length() < 1) {
e
没有合适的资源?快使用搜索试试~ 我知道了~
网络爬虫SearchCrawler
共2个文件
java:2个
4星 · 超过85%的资源 需积分: 9 22 下载量 14 浏览量
2011-06-29
12:22:55
上传
评论
收藏 4KB RAR 举报
温馨提示
该程序是利用Java实现的搜索程序,可以搜索出摸个网站内的所有网页。可以对输入的网址利用层次和数量限制进行搜索。现在所有搜索引擎都是用利用爬虫进行网页的搜索的。 比如输入www.***.com 限制搜索10000个网页,最多搜索5层。在程序执行完毕后,会扫描出所有的网址,并输入到D:\out1文件中。 搜索的网页数量和层次可以自己设定,不推荐进行站外搜索,同样不推荐扫描层次超过5层(其实5层已经足够了),以免超过内存容量,导致系统出错。
资源推荐
资源详情
资源评论
收起资源包目录
网络爬虫.rar (2个子文件)
网络爬虫
SearchCrawler.java 10KB
urlclass.java 667B
共 2 条
- 1
资源评论
- zmd_yd2013-01-20不知道是什么原因,在我电脑上面不能运行。希望能够给出运行步骤
- Jin铭2015-08-06还不错,正好有用
- hy315hy2012-12-30不知道为什么运行不起来啊……
- pony2014-06-21还不错,正好需要参考参考,谢谢!
- adorey2012-12-25可以定义最大搜索量和层次 不错
Forrest_brm
- 粉丝: 0
- 资源: 1
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功