【问题标题】:how to fetch content in web crawling如何在网络爬虫中获取内容
【发布时间】: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


    【解决方案1】:

    抓取算法本质上是Breadth first search,您需要维护一个未访问的 URL 队列,并且每次访问一个 URL 时,您都会将其从队列中取出,并且您需要将您从您的站点中找到的任何未访问的 URL 加入队列HTML 解析器 (SpiderLeg)。

    将 URL 添加到队列的条件取决于您,但通常您需要将 URL 与种子 URL 的距离作为停止点,这样您就不会永远遍历网络。这些规则还可能包括您对搜索感兴趣的具体内容,以便您只添加相关的 URL。

    【讨论】:

    • 干杯!!将尝试..但是到目前为止,我在不使用 queue D.S 的情况下尝试了这个,它确实可以工作,但在搜索某些单词时不会停止程序。当它找到它时,它只显示网页的链接,而不是它找到该词的所有特定 URL。想知道这样可以吗?
    • 请用您更新的代码/尝试打开另一个问题
    最近更新 更多