2014-11-16 3 views
0

일부 URL이 있습니다. html을 가리키고있는 모든 href를 href (입수)에서 가져온 모든 href를 가져오고 싶습니다. 요점은 그 "재귀"의 깊이를 설정하고자하는 것입니다 예를 들어, depth = 1 인 경우 HTML에서 href 만 필요합니다. 깊이 = 2, 나는 목록 1에서 등 href가 각에서 (가정하자 목록 1을) HTML에서하는 HREF와하는 HREF 필요한 경우jsoup를 사용하여 href를 얻는 방법

다음

내가 jsoup 사용 한 것입니다 :

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

import java.io.File; 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.ArrayList; 
import java.util.List; 

public class Parser { 
    private final static String FILE_PATH = "src/main/resources/href.txt"; 
    private List<String> result; 

    private int currentDepth; 
    private int maxDepth; 

    public Parser(int maxDepth) { 
     result = new ArrayList<String>(); 
     this.maxDepth = maxDepth; 
    } 

    public void parseURL(String url) throws IOException { 
     url = url.toLowerCase(); 
     if (!result.contains(url)) { 
      Connection connection = Jsoup.connect(url); 
      Document document = connection.get(); 
      Elements links = document.select("a[href]"); 
      for (Element link : links) { 
       String href = link.attr("href"); 
       result.add(href); 
       parseURL(link.absUrl("href")); 
       currentDepth++; 
       if (currentDepth == maxDepth) 
        return; 
      } 
     } 
    } 
} 

어떻게 수정해야 재귀 조건에 맞습니까?

답변

0

재귀 함수를 호출하기 전에 먼저 깊이를 확인해야한다고 생각합니다.

if (currentDepth >= maxDepth){ 
    // do nothing 
}else{ 
    parseURL(...) 
} 
0
public void parseURL(String url) throws IOException { 
    url = url.toLowerCase(); 
    if (!result.contains(url)) { 
     Connection connection = Jsoup.connect(url); 
     Document document = connection.get(); 
     Elements links = document.getElementsByAttribute("href"); 
     // Elements links = document.select("a[href]"); 
     for (Element link : links) { 
      String href = link.attr("href"); 
      result.add(href); 
      parseURL(link.absUrl("href")); 
      currentDepth++; 
      if (currentDepth == maxDepth) 
       return; 
     } 
    } 
} 

당신은 당신이 속성

을 지정한 방법 getElementsByAttribute(String attribute)의 모든 요소를 ​​얻을 수 있습니다, 여러분의 코드에서 이것을 시도 할 수 있습니다
관련 문제