如何在网络爬虫中获取内容

how to fetch content in web crawling

嗨!我正在尝试为 用于探索网络的蜘蛛算法实现此伪代码。 需要我的下一步伪代码的一些想法:“使用 SpiderLeg 获取内容”, 我在另一个 class SpiderLeg 中有一个方法,它有一个方法来获取该网页的所有 URL,但想知道如何在这个 class 中使用它?

// 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 的情况下尝试了此操作,它几乎可以正常工作,但在搜索某个单词时不会停止程序。

当它找到时,它只显示网页的 link,而不是它找到该词的所有特定 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)");
  }

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

将 URL 添加到队列的条件由您决定,但通常您需要保持 URL 与种子 URL 的距离作为一个停止点,这样你就不会永远遍历网络。这些规则还可能包含您感兴趣的搜索内容的详细信息,以便您仅添加相关的 URL。