【问题标题】:How to select span elements of specific container (<div> defined by CSS class) using Xpath?如何使用 Xpath 选择特定容器(由 CSS 类定义的 <div>)的 span 元素?
【发布时间】:2020-07-25 19:34:27
【问题描述】:

我有以下 HTML 结构:

  <div class="divone"><span class="my_sapn">Sports</span></div>
  <div class="divtwo"><span class="my_sapn">Arts</span></div>
  <div class="divtwo"><span class="my_sapn">Computer</span></div>
  <div class="divone"><span class="my_sapn">Fashion</span></div>
  <div class="divtwo"><span class="my_sapn">Familly</span></div>

我想要实现的是在仅具有 divone 类的 div 中获取所有具有 my_span 类的元素。
我的代码使用 my_span 类获得所有跨度,输出:Sports, Arts , Computer , Fashion , Familly
所需输出:Sports , Fashion
我的代码:

List<WebElement> MainCategory = driver.findElements(By.xpath("//span[@class=\"my_span\"]"));

PS : 我必须使用By.xpath 而不是By.classame

【问题讨论】:

    标签: java selenium xpath


    【解决方案1】:

    实现此结果的一种方法是使用以下 XPath-1.0 表达式:

    List<WebElement> MainCategory = driver.findElements(By.xpath("//div[@class='divone' and span/@class='my_span']/span"));
    

    实现相同输出的另一种方法是

    List<WebElement> MainCategory = driver.findElements(By.xpath("//span[../@class='divone' and @class='my_span']"));
    

    两种情况下的输出是一样的:

    体育
    时尚

    【讨论】:

      猜你喜欢
      • 2016-05-19
      • 2023-01-29
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多