我有任何网页网址的占位符。当我单击按钮时它应该提取元素。我必须在页面中显示元素和 xpath 值。我怎样才能做到这一点?请帮助我。
最佳答案
我不确定这是否是您想要的,但如果您需要显示每个元素的 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
关于javascript - 如何在javascript中进行元素提取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39741771/