【问题标题】:Selenium 2 - Can findElement(By.xpath) be scoped to a particular element?Selenium 2 - findElement(By.xpath) 可以限定为特定元素吗?
【发布时间】:2023-03-22 11:09:01
【问题描述】:

我见过的 findElement(By.xpath) 的所有示例搜索整个页面,例如

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

我想要实现的是:

WebElement tr = ... // find a particular table row (no problem here)
WebElement td = tr.findElement(By.xpath("/td[3]"));  // Doesn't work!

我还尝试了其他变体,但没有运气:“td[3]”、“child::td[3]”

使用“//td[3]”查找整个页面中的第一个匹配节点,即不限于我的tr。因此,当您通过 xpath 查找元素时,您调用 findElement() 的 WebElement 看起来毫无意义。

是否可以将 findElement(By.xpath) 范围限定为特定的 WebElement?

(我正在使用 Chrome,以防万一。)

请注意: By.xpath("//td[3]") 只是一个示例。我不是在寻找实现相同目标的替代方法。问题只是试图确定 foo.findElement() 在与 By.xpath 选择器一起使用时是否注意到 foo。

【问题讨论】:

    标签: selenium selenium-webdriver


    【解决方案1】:

    根据 ZzZ 的回答,我认为问题在于您尝试的查询是绝对的而不是相对的。通过使用起始/,您可以强制进行绝对搜索。而是使用 ZzZ 建议的标签名称,././/

    查看“位置路径表达式”下的XPath docs

    【讨论】:

    • 这是真的,并且在 Selenium docs 的“findElements”方法下对 WebElement 接口进行了解释。
    【解决方案2】:

    我也遇到了这个问题,并花了很多时间试图找出解决方法。这就是我想出来的:

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

    不知道为什么,但这对我有用。

    【讨论】:

    【解决方案3】:

    我认为这可能是 Selenium2 使用 xpath 的方式中的一个错误。但是,我相信我之前已经成功地使用“::ancestor”限制了范围。

    无论如何,您是否尝试过使用 Css 选择器来解决这个问题?这对你来说是一个选择吗?试试这个:

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

    这应该可以完成工作,并且与您最初尝试的相同:

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

    【讨论】:

    • 感谢 'ancestor::' 提示 - 我会试试这个。正如我在上一个答案中评论的那样,“/td[3]”只是一个例子。在可能的情况下,我确实更喜欢非 xpath 选择器(尤其是因为它们在 IE 中非常不可靠)。但这个问题纯粹是为了尝试确定您是否可以使用 xpath 进行范围查询。
    【解决方案4】:
    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..
    

    【讨论】:

    • 感谢您解决所有这些麻烦,Jay,但“/td[3]”只是一个示例。我想知道您是否可以使用 xpath 进行这种范围查询,因为在某些情况下这样做会非常方便。
    【解决方案5】:

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

    如果您只想查找 tr 的子元素,请使用相对路径而不是绝对路径。

    这应该可行:

    int index = 3;
    List<WebElement> tds = tr.findElements(By.xpath(".//td"));
    System.out.println(tds[index].getText());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-11
      • 2021-01-03
      • 2017-11-30
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多