optimize xpath

This commit is contained in:
jianxin committed 2024-12-17 19:01:12 +08:00
1 parent ae76837e41
commit 6c51209e93
1 file changed
+22 -8
+22 -8
View File
@@ -31,20 +31,34 @@
// 获取元素的 XPath // 获取元素的 XPath
function getElementXPath(element) { function getElementXPath(element) {
let path = []; if (element.id) {
while (element) { return `//*[@id="${element.id}"]`;
}
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; let index = 1;
let sibling = element.previousElementSibling; while (sibling.previousElementSibling) {
while (sibling) { sibling = sibling.previousElementSibling;
if (sibling.nodeName === element.nodeName) { if (sibling.nodeName.toLowerCase() === selector) {
index++; index++;
} }
sibling = sibling.previousElementSibling;
} }
path.unshift(`${element.nodeName.toLowerCase()}[${index}]`); selector += `[${index}]`;
}
parts.unshift(selector);
element = element.parentNode; element = element.parentNode;
} }
return path.length ? '/' + path.join('/') : null; return parts.length ? '/' + parts.join('/') : null;
} }
// 监听鼠标移动事件 // 监听鼠标移动事件