48 lines
1.5 KiB
JavaScript
48 lines
1.5 KiB
JavaScript
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;
|
|
}
|