Selenium 2 - Can findElement(By.xpath) be scoped to a particular element?

后端 未结 5 1105
伪装坚强ぢ
伪装坚强ぢ 2021-01-11 12:21

All the examples of findElement(By.xpath) I\'ve seen search the whole page, e.g.

WebElement td = driver.findElement(By.xpath(\"//td[3]\"));

相关标签:
5条回答
  • 2021-01-11 12:55
    what i m understanding that u want to retrieve a particular td from a tr, so here's a snippet you can try it with your code to find 3rd td...
    
    
    
    WebElement tr=//...find a particular table row 
        List<WebElement> columns = tr.findElements(By.tagName("td"));
        Iterator<WebElement> j = columns.iterator();
        int count=0;
        while(j.hasNext())  
                {   
                    WebElement column = j.next();
                    if(count==2)
                    {
                        System.out.print(column.getText());
                    }
                    count++;
                }
    
    You can change count value in if condition to retrieve another td..
    Hope this will help you..
    
    0 讨论(0)
  • 2021-01-11 12:56

    I think this might be a bug in the way that Selenium2 uses xpath. However, I believe I've successfully limited the scope using "::ancestor" before.

    In any event, have you tried using Css Selectors to solve this? Is that an option for you? Try this:

    tr.findElement(By.cssSelectors("td:nth-of-type(3)"));

    This should do the job and is the equivalent of what you tried initially:

    tr.findElement(By.xpath("//td[3]"));

    0 讨论(0)
  • 2021-01-11 13:03

    WebElement td = tr.findElement(By.xpath("/td[3]"));

    If you only want to to find the child elements of the tr use a relative path not an absolute.

    This should work:

    int index = 3;
    List<WebElement> tds = tr.findElements(By.xpath(".//td"));
    System.out.println(tds[index].getText());
    
    0 讨论(0)
  • 2021-01-11 13:09

    I also ran into this issue and spent quite a lot of time trying to figure out the workaround. And this is what I figured out:

    WebElement td = tr.findElement(By.xpath("td[3]"));
    

    Not sure why, but this works for me.

    0 讨论(0)
  • 2021-01-11 13:10

    Based on ZzZ's answer I think the issue is that the queries you are trying are absolute instead of relative. By using a starting / you force absolute search. Instead use the tag name as ZzZ suggested, ./ or .//.

    Look in the XPath docs under "Location Path Expression"

    0 讨论(0)
提交回复
热议问题