Recently, I tried to generate XPath for an HTML element using available coding snippets. Most of them are generated using class names. However, since React MUI uses dynamic class names through make-styles, the above method of generating XPaths is not always reliable. Therefore, I developed a code that uses only IDs to generate XPath. If you are also facing the same issue as mine, this will be useful for you.
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
}

1 comment:

  1. 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

    ReplyDelete

Blogroll

Popular Posts