optimize xpath

This commit is contained in:
jianxin committed 2024-12-22 21:47:22 +08:00
1 parent 6f81dba0b6
commit bc19b204e1
5 files changed
+235 -34

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
function getElementXPath(element) {
if (element.id) {
return `//*[@id="${element.id}"]`;
}
// 判断元素是否在iframe中
let currentElement = element;
let iframe = null;
while (currentElement) {
if (currentElement.tagName && currentElement.tagName.toLowerCase() === 'iframe') {
iframe = currentElement;
break;
}
currentElement = currentElement.parentNode;
}
if (iframe) {
const iframeXPath = getElementXPath(iframe);
const elementXPath = getElementXPath(element);
return iframeXPath + elementXPath;
}
const parts = [];
while (element && element.nodeType === Node.ELEMENT_NODE) {
let selector = element.nodeName.toLowerCase();
if (element.className) {
selector += `[@class="${element.className}"]`;
} else if (element.textContent.trim()) {
selector += `[text()="${element.textContent.trim()}"]`;
} else if (element.id) {
selector += `[@id="${element.id}"]`;
} else {
let sibling = element;
let index = 1;
while (sibling.previousElementSibling) {
sibling = sibling.previousElementSibling;
if (sibling.nodeName.toLowerCase() === selector) {
index++;
}
}
selector += `[${index}]`;
}
parts.unshift(selector);
element = element.parentNode;
}
return parts.length ? '/' + parts.join('/') : null;
}