2016-09-28 2 views
0

나는 웹 페이지 URL이있는 자리 표시자를 가지고 있습니다. 버튼을 클릭하면 요소를 추출해야합니다. 내 페이지에 요소 및 xpath 값을 표시해야합니다. 내가 어떻게 할 수 있니? 도와주세요.자바 스크립트에서 요소 추출을 수행하는 방법?

+1

당신은 당신이 뭘 하려는지의 예를 들어 주실 수 있습니까? 네가 묻고있는 것이 나에게 아직도 불분명하다. – serge1peshcoff

+0

예. 샘플 이미지를 추가했습니다. url을 맨 위에 놓았다고 가정 해 봅시다. 나가 추출 단추를 클릭 할 때. 그것은 모든 요소와 xpath 값을 액션과 버튼으로 표시해야합니다. – VSK

답변

1

은 그게 당신이 원하는 경우에 확실하지 않다,하지만 당신은 모든 요소의 XPath를 표시해야하는 경우, 여기 내 솔루션입니다 :

function buildDom(text) { 
    var div = document.createElement('div'); 
    div.innerHTML = text; 
    return div.firstChild; 
} 

function fetchAttrs(node) { // getting attributes object for element 
    return node && Array.prototype.reduce.call(node.attributes, function(list, attribute) { 
    list[attribute.name] = attribute.value; 
    return list; 
    }, {}) || {}; 
}; 

function traverseElement(element, argPrefix = "") { 
    if (element.nodeType === Node.TEXT_NODE) 
    return; // skipping text elements 

    var attrs = fetchAttrs(element) 
    var prefix = argPrefix + "/" + element.tagName; // build element path 
    if (Object.keys(attrs).length !== 0){ 
    prefix += "[" + Object.keys(attrs).map((value, index) => { 
     return "@" + value + ' = "' + attrs[value] + '"' 
    }).join(" and ") + "]" // append arguments 
    } 

    console.log(prefix); 

    var children = element.childNodes // iterating over children 
    for (var i = 0; i < children.length; i++) 
    { 
    traverseElement(children[i], prefix) 
    } 
} 

var url = "https://icanhazip.com/" // URL to load 

var xhttp = new XMLHttpRequest(); 
xhttp.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { // when loaded 
    var dom = buildDom(this.responseText); // build a DOM tree from a response string 
    traverseElement(dom) // and traverse it 
    } 
}; 
xhttp.open("GET", url, true); 
xhttp.send(); // loading needed website 
+0

고마워요. 어디 웹 페이지 URL을 전달할 수 – VSK

+0

아, 내가 잘못 이해했다. – serge1peshcoff

+0

고맙습니다. – VSK

관련 문제