Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create XPath expression programmatically

Is it possible to generate the most specific XPath expression automatically from the position of the cursor on the web page? The XPath expression would change with "onMouseMove event".

If it's possible, how would you implement it? Or is it already implemented in some Javascript or Python library? I would prefer it in Python with a combination of some web library but Javascript would be good and acceptable too.

like image 485
xralf Avatar asked Oct 09 '22 19:10

xralf


2 Answers

See the Get XPath thread in DZone Snippets for finding the XPath. See the How do I check if the mouse is over an element in jQuery? question here for identifying when the mouse cursor is over an element.

like image 72
JamieSee Avatar answered Oct 12 '22 12:10

JamieSee


I have answered an almost identical question (using jQuery) at Return XPath location with jQuery? Need some feedback on a function

If you change the click event to mouseenter you would have what you ask for..

$(document).delegate('*','mouseenter',function(){
    var path = $(this).parents().andSelf();
    var xpath='/';
    for (var i = 0; i < path.length; i++)
    {
        var nd = path[i].nodeName.toLowerCase();
        xpath += '/';
        if (nd != 'html' && nd != 'body')
        {
            xpath += nd;
            if (path[i].id != '')
            {
                xpath += '#' + path[i].id;
            }
            else
            {
                xpath += '['+ ($(path[i-1]).children().index(path[i])+1) +']';
            }
            if (path[i].className != '')
                xpath += '.' + path[i].className;
        }
        else
        {xpath += nd;}                    
    }
    $('#xpath').html(xpath); // show the xpath in an element with id xpath..
    return false;
});

Demo at http://jsfiddle.net/gaby/hsv97/25/


Update with no jQuery used.. (for modern browsers)

function getXpath(event){
    var hierarchy = [],
        current = event.srcElement||event.originalTarget;
    while (current.parentNode){
        hierarchy.unshift(current);
        current = current.parentNode;
    }
    var xPath = hierarchy.map(function(el,i){
            return el.nodeName.toLowerCase() + ((el.id !== '') ? '#'+el.id : '') + ((el.className !== '') ? '.'+el.className.split(' ').join('.') : '');
        }).join('/');
    document.getElementById('xpath').innerHTML = xPath;
    return xPath;
}

if (document.addEventListener){
    document.addEventListener('mouseover', getXpath, false);
} else {
    document.onmouseover = getXpath;
}

Demo at http://jsfiddle.net/gaby/hsv97/29/

like image 40
Gabriele Petrioli Avatar answered Oct 12 '22 12:10

Gabriele Petrioli