【问题标题】:Selenium: finding elements in searchContextSelenium:在 searchContext 中查找元素
【发布时间】:2012-08-01 22:27:35
【问题描述】:

大家! 我遇到了以下问题: 有一些

SearchContext searchContext;
By by;

可以是 WebDriver 或 WebElement。 假设它们都已经初始化(我们不知道如何); 现在我们想用这样的 xpath 找到元素,似乎要遵循

List<WebElement> elements = searchContext.findElements(by);

但是,如果 searchContext 是 WebElement 并且

by = By.xpath("//div");

这行不通! (不会找到任何元素),因为我们需要这样做

by = By.xpath("./div");

(见Locating child nodes of WebElements in selenium) 但是,正如我所提到的,我们对 by 是如何初始化的一无所知;

所以,我的问题是:尽管存在上述问题,有没有办法正确找到元素? 我有两个变量:by 和 searchContext,我应该在 searchContext 中找到指定的元素。

【问题讨论】:

    标签: xpath selenium webdriver


    【解决方案1】:

    你可以用一些辅助方法来做,如果发生这种情况会抛出异常

    public List<WebElement> returnSearchContext(By by, SearchContext searchContext){
      List<WebElement> elements = searchContext.findElements(by);
      if (elements.getSize()>0){
         return elements;}
       else{
         throw new ElementNotFoundException();
       }
    }
    

    我在没有访问任何 IDE 的情况下编写此代码,因此我的示例代码中可能会出现一些错误。例如,我认为异常需要一些参数。但我希望你能明白。

    【讨论】:

    • 感谢您的回复!=) 不幸的是,这并不能解决问题,它只是一种处理失败的方法。这是我的错——我的问题表述不够清楚。我让它更具体。
    • 愚蠢的我 :) 问题只是“那么简单”吗?含义——当搜索上下文是WebElement时,真的只需要找到子DIV,还是很复杂?
    【解决方案2】:

    据我了解,现在有办法做到这一点。 唯一的方法是手动正确指定 By.xpath:

    By child = By.xpath("/div");
    By descendant = By.xpath("//div");
    

    如果是 WebDriver.isAssignableFrom(searchCONtext.getCLass()), 和

    By child = By.xpath("div");
    By descendant = By.xpath(".//div");
    

    在 WebElement.isAssignableFrom(searchCONtext.getCLass()) 的情况下。 恕我直言,这很糟糕。

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 2017-12-03
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多