【发布时间】:2025-12-26 03:00:06
【问题描述】:
嗨!我正在尝试为 用于探索网络的蜘蛛算法实现此伪代码。 我的下一步伪代码需要一些想法:“use SpiderLeg to fetch content”, 我在另一个类 SpiderLeg 中有一个方法,它有一个方法可以获取该网页的所有 URL,但想知道如何在这个类中使用它??
// method to crawl web and print out all URLs that the spider visit
public List<String> crawl(String url, String keyword) throws IOException{
String currentUrl;
// while list of unvisited URLs is not empty
while(unvisited != null ){
// take URL from list
currentUrl = unvisited.get(0);
//using spiderLeg to fetch content
SpiderLeg leg = new SpiderLeg();
}
return unvisited;
}
干杯!!会尝试...但是我在不使用队列 D.S 的情况下尝试了这个,它几乎可以工作,但在搜索某些单词时不会停止程序。
当它找到它时,它只显示网页的链接,而不是它找到该词的所有特定 URL。 想知道是否可以这样做?
private static final int MAX_PAGES_TO_SEARCH = 10;
private Set<String> pagesVisited = new HashSet<String>();
private List<String> pagesToVisit = new LinkedList<String>();
public void crawl(String url, String searchWord)
{
while(this.pagesVisited.size() < MAX_PAGES_TO_SEARCH)
{
String currentUrl;
SpiderLeg leg = new SpiderLeg();
if(this.pagesToVisit.isEmpty())
{
currentUrl = url;
this.pagesVisited.add(url);
}
else
{
currentUrl = this.nextUrl();
}
leg.getHyperlink(currentUrl);
boolean success = leg.searchForWord(searchWord);
if(success)
{
System.out.println(String.format("**Success** Word %s found at %s", searchWord, currentUrl));
break;
}
this.pagesToVisit.addAll(leg.getLinks());
}
System.out.println("\n**Done** Visited " + this.pagesVisited.size() + " web page(s)");
}
【问题讨论】:
标签: java algorithm web-crawler scrapy-spider