2017-10-12 8 views
0

해당 텍스트가있는 모든 요소를 ​​얻을 수 있습니다 jQuery에서와 마찬가지로. html 본문의 일반 텍스트를 가져와야하지만 그뿐만 아니라 해당 요소와 숫자를 가져와야합니다. IE는 : 일반 텍스트가 세 번째 단락 요소에서 발견 된 경우, 나는 같은 것이다 :DOM 탐색은 - 어떻게 당신이 HTML 텍스트 트래버스를 구문 분석 할 수 있습니다 <strong>힘내라</strong>의 <strong>노드 서버 측</strong>에 jQuery를 유사한 라이브러리를 사용하고 그래서

{ 
    text: <element plaintext>, 
    element: "p-3" 
} 

을 나는 현재이 작업을 수행하려고 다음과 같은 기능이 있습니다 내가가는 건가요

var plaintext_elements = traverse_tree($('body'));  

function traverse_tree(root, found_elements = {}, return_array = []) { 
    if (root.children().length) { 
     //root has children, call traverse_tree on that subtree 
     traverse_tree(root.children().first(), found_elements, return_array); 
    } 
    root.nextAll().each(function(i, elem) { 
     if ($(elem).children().length) { 
      //if the element has children call traverse_tree on the element's first child 
      traverse_tree($(elem).children().first(), found_elements, return_array) 
     } 
     else { 
      if (!found_elements[$(elem)[0].name]) { 
       found_elements[$(elem)[0].name] = 1; 
      } 
      else { 
       found_elements[$(elem)[0].name]++ 
      } 
      if ($(elem).text() && $(elem).text != '') { 
       return_array.push({ 
        text: $(elem).text(), 
        element: $(elem)[0].name + '-' + found_elements[$(elem)[0].name] 
       }) 
      } 
     } 
    }) 


    if (root[0].name == 'body') { 
     return return_array; 
    } 

} 

을 올바른 방향으로, 다른 것을 시도해야합니까? 이것에 대한 도움을 주시면 감사하겠습니다. 다시 이것은 이 아니라 jQuery이지만 서버 측 Cheerio입니다.

+0

를 사용하는 경우 탐색의 많은이 당신이 가진 요소를 무시 행복 것 같습니다 필요하지 않은 생각 (그들은 그러나 매우 유사) children _and_ text? '

text

dt
' – Matt

+0

의 'dt'와 마찬가지로, 그 문제는 내가 만난 문제 중 하나입니다. 나는 'blah blah blah'과 같이 td와 a 모두에 대해 "어쩌구 저쩌구"라고 말하면서 중복 된 톤을 얻지 않고도이 사건을 처리하는 방법을 모르겠습니다. – janedoe

답변

0

난 당신이 현재 코드에서 * CSS를 선택

function textElements($){ 
    const found = {} 
    return $('body *').map(function(el){ 
    if ($(this).children().length || $(this).text() === '') return 
    found[this.name] = found[this.name] ? 1 + found[this.name] : 1 
    return { 
     text: $(this).text(), 
     element: `${this.name}-${found[this.name]}`, 
    } 
    }).get() 
} 

textElements(cheerio.load(html) 
+0

은 작동하는 것처럼 보이지만 html이 ' hello, 여기를 클릭하면 여기를 클릭하면'결과를 볼 때 문제가 발생합니다. 여기에는 "여기를 클릭하십시오"가 표시됩니다. – janedoe