optimize xpath
This commit is contained in:
1 parent
ae76837e41
commit
6c51209e93
1 file changed
+24
-10
+24
-10
@@ -31,20 +31,34 @@
|
||||
|
||||
// 获取元素的 XPath
|
||||
function getElementXPath(element) {
|
||||
let path = [];
|
||||
while (element) {
|
||||
let index = 1;
|
||||
let sibling = element.previousElementSibling;
|
||||
while (sibling) {
|
||||
if (sibling.nodeName === element.nodeName) {
|
||||
index++;
|
||||
if (element.id) {
|
||||
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;
|
||||
while (sibling.previousElementSibling) {
|
||||
sibling = sibling.previousElementSibling;
|
||||
if (sibling.nodeName.toLowerCase() === selector) {
|
||||
index++;
|
||||
}
|
||||
}
|
||||
sibling = sibling.previousElementSibling;
|
||||
selector += `[${index}]`;
|
||||
}
|
||||
path.unshift(`${element.nodeName.toLowerCase()}[${index}]`);
|
||||
parts.unshift(selector);
|
||||
element = element.parentNode;
|
||||
}
|
||||
return path.length ? '/' + path.join('/') : null;
|
||||
return parts.length ? '/' + parts.join('/') : null;
|
||||
}
|
||||
|
||||
// 监听鼠标移动事件
|
||||
|
||||
Reference in new issue
Block a user