2017-09-05 1 views
1

내 검색 엔진의 경우 태그 및 텍스트를 기반으로 HTML 문서를 인덱싱하려고합니다. 이렇게하면 할 수 있습니다. 단락에 헤드 라인을 상속합니다.자바, 브라우저에서 표시 한 것과 동일한 순서로 DOM의 태그로 텍스트 콘텐츠 가져 오기

<body> 
    <div1> one 
     <h2> two </h2> 
     <div2> three 
     <div3> four </div3> 
     </div2> 
     <p> five </p> 
    six 
    </div1> 
    </body> 

내가 출력으로 원하는 것은 :

div1 : 하나, H2 : 두, DIV2 세, div3 나는 다음과 같은 DOM을 준 예를 들어

: 4, p : 5, div1 : 6
(브라우저에서 표시하는 순서와 동일)

그러나, Jsoup와 난 단지 얻을 수 있습니다 :

Document htmlDocument = Jsoup.parse(htmlExample); 
Elements allTagsInOrderOfAppearance = htmlDocument.body().select("*"); 

//either 1. 
for (Element element : allTagsInOrderOfAppearance){ 
     System.out.println(element.tagName() + ": " + element.ownText()); 
    } 

1. 출력 :
'div1 : 1 ~ 6, H2 : 두, DIV2 세, div3, 사, P : 오'

//or 2. 
for (Element element : allTagsInOrderOfAppearance){ 
      if(element.parent().ownText().isEmpty()){ 
       System.out.println(element.tagName() + ": " + element.text()); 
      } 
    } 

2. 출력 :
'div1 : 하나, 둘, 셋, 넷, 다섯, 여섯'

jsoup 또는 다른 libary를 사용하여 원하는 출력을 얻는 다른 방법이 있습니까?

답변

0

요소 노드 만보고 있습니다. 원하는 출력 (body 요소의 두 텍스트 노드가 별도로 표시되는)을 얻으려면 요소의 텍스트 노드를 반복해야합니다. 이를 수행하는 가장 쉬운 방법은 재귀 함수가있는 childNodes을 사용하는 것입니다. 이 라인 함께를 (개념, 당신은 아마 그것을 조정할해야합니다) :

public void visitNode(Node node) { 
    if (node instanceof Element) { 
     Element e = (Element)node; 
     System.out.println(e.tagName()); 
     for (Node child : e.childNodes()) { 
      this.visitNode(child); 
     } 
    } else if (node instanceof TextNode) { 
     System.out.println(((TextNode)node).text()); 
    } 
} 

그런 일 킥오프하는 body 요소를 호출합니다.

노드에서 시작하여 은 정확히 원하는 출력을 생성하지 않습니다. 이 버전은 노드 목록에서 시작하여 수행합니다

static void visitNodes(List<Node> nodes, String prefix) { 
    for (Node child : nodes) { 
     if (child instanceof Element) { 
      Element e = (Element)child; 
      visitNodes(e.childNodes(), e.tagName() + ":"); 
     } else if (child instanceof TextNode) { 
      if (prefix != null) { 
       System.out.print(prefix); 
      } 
      System.out.println(((TextNode)child).text()); 
     } 
    } 
} 

전체 작업 버전 :

import java.util.List; 
import org.jsoup.*; 
import org.jsoup.nodes.*; 

public class Example { 
    public static void main(String[] args) throws Exception { 
     String htmlExample = "<body>" + 
      "<div1> one" + 
       "<h2> two </h2>" + 
       "<div2> three" + 
       "<div3> four </div3>" + 
       "</div2>" + 
       "<p> five </p> " + 
      "six" + 
      "</div1>" + 
      "</body>"; 
     Document htmlDocument = Jsoup.parse(htmlExample); 
     visitNodes(htmlDocument.body().childNodes()); 
    } 

    static void visitNodes(List<Node> nodes) { 
     visitNodes(nodes, null); 
    } 
    static void visitNodes(List<Node> nodes, String prefix) { 
     for (Node child : nodes) { 
      if (child instanceof Element) { 
       Element e = (Element)child; 
       visitNodes(e.childNodes(), e.tagName() + ":"); 
      } else if (child instanceof TextNode) { 
       if (prefix != null) { 
        System.out.print(prefix); 
       } 
       System.out.println(((TextNode)child).text()); 
      } 
     } 
    } 
} 
+0

너무 감사합니다! 그것은 훨씬 더 복잡한 HTML로 첫 번째 시도에서 완벽하게 작동했습니다. 나에게 많은 연구를 구해줬다. – sony

관련 문제