Java编程——应用开源框架实现简易web搜索

引言

应用 Java 的开源库,编写一个搜索引擎,这个引擎能爬取一个网站的内容。并根据网页内容进行深度爬取,获取所有相关的网页地址和内容,用户可以通过关键词,搜索所有相关的网址。

具体功能

(1) 用户可以指定爬取一个url对应的网页的内容。
(2) 对网页内容进行解析,并获取其中所有的url链接地址。
(3) 用户可以设定爬取深度,代表着从初始url对应的页面开始,可以爬取其中所有的url对应的网页内的url,以此类推。深度越大,能爬取到的网站越多。
(4) 对爬取到的url内容进行保存、建立索引。建立索引的内容是url地址本身,和url对应的网页标题。
(5) 用户可以通过关键词对网址进行搜索,找出有该关键词的url地址。
(6) 建立索引和搜索索引的过程能智能识别中文关键词,能对关键词进行分词操作。
(7) 用户可以指定保存索引的地址、初始url、爬取深度、进行搜索的关键词和最大匹配项。

开源框架

  • Lucene
  • Jsoup

源码

爬虫部分:Spider.java
package webCrawler.Spider;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import webCrawler.Index.BuildIndex;

/**
 * @author lannooo
 */

public class Spider {
   
    ArrayList<String> URLs;
    private String startURL;
    private int digLevel;

    /**
     * @param startURL 爬虫的起始URL
     * @param digLevel 爬取深度
     */
    public Spider(String startURL, int digLevel){
        this.startURL = startURL;
        this.digLevel = digLevel;
        this.URLs = new ArrayList<>();
    }

    /**
     * @param level 当前爬取的深度剩余
     * @param arrayList 需要进行下一轮爬去的URL集
     * @return 从一格url集爬取到的新的URL集
     * @throws IOException
     */
    public ArrayList<String> getLevelURLs(int level, ArrayList<String> arrayList) 
            throws IOException{
        ArrayList<String> total = null;
        if(level>0){            
            total = new ArrayList<>();
            for(String url: arrayList){
                /*对于每个arrayList中的URL,首先解析其网页内容,并获得里面所有URL项*/
                for(String each: getBareLinks(url)){
                    total.add(each);
                }
            }
            /*用HashSet这个容器将total里面重复项删除*/
            HashSet<String> hashSet = new HashSet<>(total);
            total = new ArrayList<>(hashSet);
        }
        return total;
    }

    /**
     * 从startURL开始,爬取所有相关URLs
     * @throws IOException
     */
    public void getAll() throws IOException{
        ArrayList<String> newURLs;
        ArrayList<String> currentURLs = new ArrayList<>();
        /*把startURL加入currentURLs这个列表中,从这个url开始爬*/
        currentURLs.add(startURL);
        for(int i=digLevel; i>0; i--){
            /*
             * 对于每一层,都要获取一次由这个url引申出去的url集
             * 然后把当前集的已经爬去过的url加入到总的URL集中
             * 最后newURLs作为新的需要进行深度爬取的集进入下一轮循环
             */
            System.out.println("Dig into lev
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值