您的位置:首页 > 产品设计 > UI/UE

初试 爬虫机器人 + luence全文检索

2015-03-02 14:31 225 查看
1、网上有很多的开源爬虫机器人。这里从网上找了一个简单在爬虫机器人代码。使用到了以下jar包:

commons-httpclient-3.0.1.jar

commons-logging-1.1.1.jar

htmlparser.jar

代码如下:

LinkQueue类:定义已访问队列,待访问队列和爬取得URL的哈希表,包括出队列,入队列,判断队列是否空等操作。

package webspider;

import java.util.HashSet;

import java.util.PriorityQueue;

import java.util.Set;

import java.util.Queue;

/**

* 定义已访问队列,待访问队列和爬取得URL的哈希表,包括出队列,入队列,判断队列是否空等操作。

* @author yang.chao3

*

*/

public class LinkQueue

{

// 已访问的 url 集合

private static Set<String> visitedUrl = new HashSet<String>();

// 待访问的 url 集合

private static Queue<String> unVisitedUrl = new PriorityQueue<String>();

// 获得URL队列

public static Queue<String> 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 只被访问一次:如果URL既不在已访问的队列,又不在未访问的对列,说明此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();

}

}

HtmlParserTool类:用来获得网页中的超链接(包括a标签,frame中的src等等),即为了得到子节点的URL。

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;

/**

* 定义HtmlParserTool类,用来获得网页中的超链接(包括a标签,frame中的src等等),即为了得到子节点的URL

* @author yang.chao3

*

*/

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");

// parser.setEncoding("gb2312");

// 过滤 <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 (Exception e)

{

e.printStackTrace();

return null;

}

return links;

}

}

接口:LinkFilter

package webspider;

public interface LinkFilter

{

public boolean accept(String url);

}

类:DownLoadFile:根据得到的url,爬取网页内容,下载到本地保存。

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;

/**

* 根据得到的url,爬取网页内容,下载到本地保存。

* @author yang.chao3

*

*/

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)

{

System.out.println("++++++++++++++++++download:"+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 = "e:\\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;

}

}

启动类:MyCrawler,运行此类即可开始爬行。

package webspider;

import java.util.Set;

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.baicu.com"))

return true;

else

return false;

}

};

// 初始化 URL 队列

initCrawlerWithSeeds(seeds);

// 循环条件:待抓取的链接不空且抓取的网页不多于1000

while (!LinkQueue.unVisitedUrlsEmpty() && LinkQueue.getVisitedUrlNum() <= 5000)

{

// 队头URL出队列

String visitUrl = (String) LinkQueue.unVisitedUrlDeQueue();

if (visitUrl == null)

{

continue;

}

DownLoadFile downLoader = new DownLoadFile();

// 下载网页

downLoader.downloadFile(visitUrl);

// 该 url 放入到已访问的 URL 中

LinkQueue.addVisitedUrl(visitUrl);

// 提取出下载网页中的 URL

try{

Set<String> links = HtmlParserTool.extracLinks(visitUrl, filter);

// 新的未访问的 URL 入队

for (String link : links)

{

LinkQueue.addUnvisitedUrl(link);

}

}catch(Exception e)

{

e.printStackTrace();

}

}

}

// main 方法入口

public static void main(String[] args)

{

MyCrawler crawler = new MyCrawler();

crawler.crawling(new String[] { "http://www.baicu.com" });

}

}

2、 luence全文索引。使用到的luence版本:lucene-4.7.2(以下代码在此版本下可用,如使用最新的luence,代码需调整)

package webspider.lucene;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.text.ParseException;

import org.apache.lucene.analysis.Analyzer;

import org.apache.lucene.analysis.standard.StandardAnalyzer;

import org.apache.lucene.document.Document;

import org.apache.lucene.document.Field;

import org.apache.lucene.document.TextField;

import org.apache.lucene.index.DirectoryReader;

import org.apache.lucene.index.IndexReader;

import org.apache.lucene.index.IndexWriter;

import org.apache.lucene.index.IndexWriterConfig;

import org.apache.lucene.queryparser.classic.QueryParser;

import org.apache.lucene.search.Filter;

import org.apache.lucene.search.IndexSearcher;

import org.apache.lucene.search.Query;

import org.apache.lucene.search.ScoreDoc;

import org.apache.lucene.search.TopDocs;

import org.apache.lucene.store.Directory;

import org.apache.lucene.store.FSDirectory;

import org.apache.lucene.util.Version;

public class LuceneIndex {

//该函数用于创建索引。可以将其写成一个单独的类。

public void createIndex() throws IOException{

System.out.println("++++++++++++++++++++++++++++++createIndex");

//数据存放文件夹

File f_doc=new File("E:\\spider");

//索引存放文件夹

File f_idx=new File("E:\\spider\\index");

//directory参数,用于传入IndexWriter

Directory directory=FSDirectory.open(f_idx);

//conf参数,用于传入IndexWriter.

IndexWriterConfig conf=new IndexWriterConfig(Version.LUCENE_47,new StandardAnalyzer(Version.LUCENE_47));

IndexWriter writer=new IndexWriter(directory,conf);

//对数据文件夹下面的所有文件建立索引;

File[] textFiles =f_doc.listFiles();

for(int i=0;i<textFiles.length;i++)

{

if(textFiles[i].isFile())

{

Document document=new Document();//注意,这个Document必须在循环中创建

System.out.println( " File"+ textFiles[i].getCanonicalPath() +"正在被索引 . " );

FileInputStream temp=new FileInputStream (textFiles[i]);

//获取文件内容

int len=temp.available();

byte[] buffer=new byte[len];

temp.read(buffer);

temp.close();

String content = new String(buffer, "GBK"); //测试发现需要转换编码

// String content=new String(buffer);

// System.out.println("content = "+ content);//测试文件内容

//加入Field

document.add(new Field("path", textFiles[i].getPath(), TextField.TYPE_STORED));

document.add(new Field("body", content, TextField.TYPE_STORED));

writer.addDocument(document);

writer.commit();//必须先提交,不然的会报错!

}

}

System.out.println("索引的数目:"+writer.numDocs());

writer.close();

}

//查询函数

public void TestQuery(String querystring) throws IOException,ParseException, org.apache.lucene.queryparser.classic.ParseException{

//创建一个IndexSearcher

File f=new File("E:\\spider\\index");

Directory directory =FSDirectory.open(f);

IndexReader ireader=DirectoryReader.open(directory);

IndexSearcher searcher=new IndexSearcher(ireader);//这个和以前的版本有所变化。

//查询词解析

Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_47);

QueryParser parser=new QueryParser(Version.LUCENE_47,"body",analyzer);

Query query=parser.parse(querystring);

//以前的Hits已经不再使用。直接使用TopDocs即可。

Filter filter = null;

TopDocs topDocs = searcher.search(query, filter, 10);//最后一个参数,限制查询结果的条目。

System.out.println("总共有【" + topDocs.totalHits + "】条匹配结果");

//显示结果

for (ScoreDoc scoreDoc : topDocs.scoreDocs)

{

//文档内部编

int index = scoreDoc.doc;

//根据编号取出相应的文档

Document doc =searcher.doc(index);

System.out.println("------------"+index+1+"----------------");

System.out.println("path = " + doc.get("path"));

// System.out.println("content = " + doc.get("body"));

}

ireader.close();

}

//主函数

public static void main(String[] args) throws IOException, ParseException, org.apache.lucene.queryparser.classic.ParseException{

LuceneIndex ix=new LuceneIndex();

ix.createIndex();//该句用于创建索引,第一次运行时将"//"去掉,以后就加上注释,不然索引会重复创建。

String querystring="的"; //检索词

System.out.println("您的检索词为:【"+querystring+"】");

ix.TestQuery(querystring);

System.out.println("检索结束 ----");

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: