Find an element by text and get xpath - selenium webdriver junit

后端 未结 11 720
情深已故
情深已故 2020-12-03 04:17

I have a table with 9 rows and 6 columns in my webpage. I want to search for a text \"MakeGoodDisabled-Programwise_09_44_38_461(n)\" and get the xpath of the cell. I have us

11条回答
  •  無奈伤痛
    2020-12-03 04:31

    You can generate xpaths with JavaScript:

    function getPathTo(element) {
    
        // only generate xpaths for elements which contain a particular text:
        if (element.innerText == "MakeGoodDisabled-Programwise_09_44_38_461(n)") {
    
            // use id to produce relative paths rather than absolute, whenever possible
            if ((element.id !== '') && (element.id != 'undefined')) {
                return 'id(\"' + element.id + '\")';
            }
    
            // stop looping when you get to the body tag
            if (element === document.body) {
                return element.tagName;
            }
    
            // calculate position among siblings
            var ix = 0; 
            var siblings = element.parentNode.childNodes;
            for (var i = 0; i < siblings.length; i++) {
                var sibling = siblings[i];
                if (sibling === element) {
                    return getPathTo(element.parentNode) + '/' + element.tagName + '[' + (ix + 1) + ']';
                }
                if (sibling.nodeType === 1 && sibling.tagName === element.tagName) {
                    ix++;
                }
            }
        }
    }
    
    // put all matching xpaths in an array
    var allXPaths = []; 
    
    // if you know the particular tag you are looking for, replace * below to optimize 
    var allTags = document.getElementsByTagName('*');
    for (i = 0; i < allTags.length; i++) {
        if ((getPathTo(allTags[i]).indexOf('/HEAD') == -1) && (getPathTo(allTags[i]).indexOf('undefined') == -1)) {
            allXPaths.push(getPathTo(allTags[i]));
            console.log(getPathTo(allTags[i]));
        }
    }
    return allXPaths;
    

    If you put that JavaScript in a String called getXPaths then in Java, you can execute it like this:

    ArrayList xpaths = (ArrayList) js.executeScript(getXPaths);
    

    It returns an array rather than a String, because if your page happens to have fewer or more elements with matching tagname/innerText, You'll want to know. You can tell by the size of the array.

提交回复
热议问题