export const generateXPathWithNearestParentId = (element) => {
let path = '';
let nearestParentId = null;
// Check if the current element's has an ID
if (element.id) {
nearestParentId = element.id;
}
while (!nearestParentId && element !== document.body) {
const tagName = element.tagName.toLowerCase();
let index = 1;
let sibling = element.previousElementSibling;
while (sibling) {
if (sibling.tagName.toLowerCase() === tagName) {
index += 1;
}
sibling = sibling.previousElementSibling;
}
if (index === 1) {
path = `/${tagName}${path}`;
} else {
path = `/${tagName}[${index}]${path}`;
}
// Check if the current element's parent has an ID
if (element.parentElement.id) {
nearestParentId = element.parentElement.id;
break; // Stop searching when we find the nearest parent with an ID
}
element = element.parentElement;
}
if (nearestParentId && nearestParentId !== 'doodlemars-nav-gpt-section') {
path = `//*[@id='${nearestParentId}']${path}`;
return path;
}
return null; // No parent with an ID found
}
Incredible guide! Generating XPATH for HTML elements without relying on class names is a valuable skill for developers. This article not only explains the process clearly but also empowers developers to enhance their web scraping and automation projects. Generating XPATH for HTML elements
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThanks for sharing this practical solution. Using IDs instead of dynamic class names for XPath generation is a smart approach, especially for React MUI projects where class names change frequently. I appreciate the clear explanation and code example. Just like a reliable outdoor advertising agency focuses on consistency for long-term results, stable element selectors make automation much more dependable.
ReplyDelete