在 Java 中以递归方式从网页检索链接



我正在开发一个简化的网站下载器(编程作业),我必须递归浏览给定 url 中的链接并将各个页面下载到我的本地目录。

我已经有一个函数可以从单个页面检索所有超链接(href 属性),Set<String> retrieveLinksOnPage(URL url) .此函数返回超链接向量。我被告知要下载最高 4 级的页面。(0 级为主页)因此,我基本上想检索站点中的所有链接,但我很难提出递归算法。最后,我打算像这样调用我的函数:

retrieveAllLinksFromSite("http://www.example.com/ldsjf.html",0)

Set<String> Links=new Set<String>();
Set<String> retrieveAllLinksFromSite (URL url, int Level,Set<String> Links)
{
    if(Level==4)
       return;
    else{
        //retrieveLinksOnPage(url,0);
        //I'm pretty Lost Actually!
        }
}

谢谢!

这是伪代码:

Set<String> retrieveAllLinksFromSite(int Level, Set<String> Links) {
    if (Level < 5) {
        Set<String> local_links =  new HashSet<String>();
        for (String link : Links) {
            // do download link
            Set<String> new_links = ;// do parsing the downloaded html of link;
            local_links.addAll(retrieveAllLinksFromSite(Level+1, new_links));
        }
        return local_links;
    } else {
        return Links;
    }
}

您需要自己在评论中实现内容。要从给定的单个链接运行该函数,您需要创建一组仅包含一个初始链接的初始链接。但是,如果您有多个初始链接,它也可以工作。

Set<String> initial_link_set = new HashSet();
initial_link_set.add("http://abc.com/");
Set<String> final_link_set = retrieveAllLinksFromSite(1, initial_link_set);
您可以使用

HashMap而不是Vector来存储链接及其级别(因为您需要递归地将所有链接降低到级别 4)

另外,它会是这样的(只是给出一个整体提示):

HashMap Links=new HashMap();
void retrieveAllLinksFromSite (URL url, int Level)
{
    if(Level==4)
       return;
    else{
        retrieve the links on current page and for each retrieved link,
        do {
           download the link
           Links.put(the retrieved url,Level)  // store the link with level in hashmap
           retrieveAllLinksFromSite (the retrieved url ,Level+1) //recursively call for
 further levels
            }
        }
}

最新更新