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

后端 未结 11 716
情深已故
情深已故 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:19

    My intention is to find a text in a table and get the corresponding next column value in the same row. I thought that I will replace the column number found by fetching the xpath with the column number I want. is there a better way to do it

    Of course there's a way. Here's one possible solution.

    Get all the rows:

    While (iterate over row)
         While(Iterate over column)
               if(column.Text=='YOUR_MATCH'){
                 int voila=column.Index
               }
        }
    }
    

    Now you can simply move to that particular index for the other rows; or you could use xpath like .../tr/td[voila] to retrieve all cells for that particular column.

    I've written an approach, please don't take to be real-working-code!

    0 讨论(0)
  • 2020-12-03 04:19

    The question which you asked does not make any sense to me. I guess there might be a strong reason for you to 'want to do it' !

    Your line of code

     String xpath = driver.findElement(By.name(test)).getAttribute("xpath");
    

    will not return anything because there is no attribute 'xpath' in html elements. Please get your basics clear on to what xpath means??

    if i have an html element as shown below

    <input name = "username" value = "Name" readonly ="readonly">
    

    i can get the values of attribute by using

    driver.findElement(By.name("username").getAttribute("value");  // returns 'Name'
    

    This will give me value of 'value' attribute

    or

    driver.findElement(By.name("username").getAttribute("readonly");  // returns 'readonly'
    

    same as above !

    0 讨论(0)
  • 2020-12-03 04:20

    Almost the same situation to me:

    I have an element in the table, but I don't know in which column it's located (like some username across all the usernames). I need to find particular string with username and click "activate" button just for this user. (the username text locates in the 2nd column which is td[2] and the button locates in the 5th column which is td[5]). So I need to run all columns one by one to find the user and then click it's button:

    for (int iter = 1;; iter++) {
                    try {
                        if (iter == 1) {
                                if ((username).equals(driver.findElement(By.xpath("/html/body/div[3]/div[4]/div/form/table/tbody/tr/td[2]/a")).getText())) {
                                    driver.findElement(By.xpath("/html/body/div[3]/div[4]/div/form/table/tbody/tr/td[5]/a")).click();
                                    break;
                                }
                        }
                    } catch (Error e) {}
                    try {
                        if (iter > 1) {
                                if ((username).equals(driver.findElement(By.xpath("/html/body/div[3]/div[4]/div/form/table/tbody/tr[" + iter + "]/td[2]/a")).getText())) {
                                    driver.findElement(By.xpath("/html/body/div[3]/div[4]/div/form/table/tbody/tr[" + iter + "]/td[5]/a")).click();
                                    break;
                                }
                            }
                        } catch (Error e) {}
                    } 
              }
    
    0 讨论(0)
  • 2020-12-03 04:25

    The XPath of an element is not a definitive value. An element can be found by many XPaths.

    You cannot use Webdriver to extract an XPath and even if you could, it is unlikely to be the most efficient or sensible one, that can only be defined by the automator.

    0 讨论(0)
  • 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<String> xpaths = (ArrayList<String>) 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.

    0 讨论(0)
  • 2020-12-03 04:33

    You can also use this to crawl up and generate the xpath:

    Call the method below with

    generateXPATH(element, "");
    

    The output will be something like:

    /html[1]/body[1]/div[5]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/form[1]/div[2]/div[1]/input[2]
    

    METHOD

    private String generateXPATH(WebElement childElement, String current) {
        String childTag = childElement.getTagName();
        if(childTag.equals("html")) {
            return "/html[1]"+current;
        }
        WebElement parentElement = childElement.findElement(By.xpath("..")); 
        List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
        int count = 0;
        for(int i=0;i<childrenElements.size(); i++) {
            WebElement childrenElement = childrenElements.get(i);
            String childrenElementTag = childrenElement.getTagName();
            if(childTag.equals(childrenElementTag)) {
                count++;
            }
            if(childElement.equals(childrenElement)) {
                return generateXPATH(parentElement, "/" + childTag + "[" + count + "]"+current);
            }
        }
        return null;
    }
    
    0 讨论(0)
提交回复
热议问题