2017-04-23 1 views
0

나는 장난 삼아 놀고있다. DOM 구조에서 특정 노드를 감지하고 노드 주변에서 텍스트 데이터를 추출하는 것을 포함하는 무언가를 작성하려고합니다. 예 : 부모 노드의 텍스트, 형제 노드 등. 몇 가지 예를 연구하고 읽은 다음 이미지 노드에 대해이 작업을 수행하는 플러그인을 작성하려고했습니다. 코드의 일부노드의 주변 텍스트를 얻는 방법?

if("img".equalsIgnoreCase(nodeName) && nodeType == Node.ELEMENT_NODE){ 
      String imageUrl = "No Url"; 
      String altText = "No Text"; 
      String imageName = "No Image Name"; //For the sake of simpler code, default values set to 
               //avoid nullpointerException in findMatches method 

      NamedNodeMap attributes = currentNode.getAttributes(); 
      List<String>ParentNodesText = new ArrayList<String>(); 
      ParentNodesText = getSurroundingText(currentNode); 

      //Analyze the attributes values inside the img node. <img src="xxx" alt="myPic"> 
      for(int i = 0; i < attributes.getLength(); i++){ 
       Attr attr = (Attr)attributes.item(i); 
       if("src".equalsIgnoreCase(attr.getName())){ 
        imageUrl = getImageUrl(base, attr); 
        imageName = getImageName(imageUrl); 
       } 
       else if("alt".equalsIgnoreCase(attr.getName())){ 
        altText = attr.getValue().toLowerCase(); 
       } 
      } 

    private List<String> getSurroundingText(Node currentNode){ 

    List<String> SurroundingText = new ArrayList<String>(); 
    while(currentNode != null){ 
     if(currentNode.getNodeType() == Node.TEXT_NODE){ 
      String text = currentNode.getNodeValue().trim(); 
      SurroundingText.add(text.toLowerCase()); 
     } 

     if(currentNode.getPreviousSibling() != null && currentNode.getPreviousSibling().getNodeType() == Node.TEXT_NODE){ 
      String text = currentNode.getPreviousSibling().getNodeValue().trim(); 
      SurroundingText.add(text.toLowerCase()); 
     } 
     currentNode = currentNode.getParentNode(); 
    } 
    return SurroundingText; 
} 

이것은 제대로 작동하지 않는 것 같습니다. img 태그가 감지되면 이미지 이름과 URL이 검색되지만 더 이상 도움이되지 않습니다. getSurroundingText 모듈이 너무 못 생겨서 시도했지만 개선하지 못했습니다. 이미지와 관련이있는 텍스트를 어디서 어떻게 추출 할 수 있을지는 명확하지 않습니다. 어떤 도움을 주시겠습니까?

답변

1

당신이 올바른 궤도에있어, 다른 한편으로는,이 예제 코드의 HTML에서 살펴 : 귀하의 경우에는

<div> 
    <span>test1</span> 
    <img src="http://example.com" alt="test image" title="awesome title"> 
    <span>test2</span> 
</div> 

, 나는 문제가의 형제 노드에 있다고 생각 img 노드, 예를 들어 직접 형제 자매를 찾고 있습니다. 앞의 예제에서 노드가 span이라고 생각할 수 있습니다.이 경우에는 더미 텍스트 노드이므로 img의 형제 노드를 요청할 때 실제 텍스트가없는 빈 노드를 얻게됩니다.

이전 HTML을 <div><span>test1</span><img src="http://example.com" alt="test image" title="awesome title"><span>test2</span></div>으로 다시 작성하면 img의 형제 노드는 원하는 노드 span이됩니다.

이전 예에서 "text1"과 "text2"를 모두 얻으려는 경우, 실제로는 Node.ELEMENT_NODE을 찾아 해당 노드 내부의 텍스트를 가져올 때까지 계속 움직여야합니다. 한 가지 좋은 방법은 찾은 것을 잡아 내지 않지만 범위를 p, span, div으로 제한하여 정확도를 향상시키는 것입니다.

관련 문제