【问题标题】:Select a element that contains two span text选择包含两个跨度文本的元素
【发布时间】:2021-12-09 04:54:59
【问题描述】:
<label class=‘Fruit’>
  <span class=‘name’>Apple</span>
  <span class=‘price’>23</span>
</label>
<label class=‘Fruit’>
  <span class=‘name’>Apple</span>
  <span class=‘price’>56</span>
</label>

我正在使用Selenium 编写自动化脚本。目前,我在编写xPath 以选择第一个标签时遇到问题。但是,这两个标签具有相同的类名,并且其跨度的类名也相同。只是价格不同。在这种情况下,如何选择第一个元素?

【问题讨论】:

    标签: html selenium-webdriver xpath


    【解决方案1】:

    您可以使用如下匹配号码,

    • 要选择第一个元素://label[@class='‘Fruit’'][1]
    • 要选择第二个元素://label[@class='‘Fruit’'][2]

    需要根据Fruit namePrice选择label时,需要编写自定义的xPath

    选择第一个标签

    //label//span[text()='Apple']//following-sibling::span[text()='23']//parent::label
    

    //label//span[@class='‘name’' and text()='Apple']//following-sibling::span[@class='‘price’' and text()='23']//parent::label
    

    选择第二个标签

    //label//span[text()='Apple']//following-sibling::span[text()='56']//parent::label
    

    //label//span[@class='‘name’' and text()='Apple']//following-sibling::span[@class='‘price’' and text()='23']//parent::label
    

    【讨论】:

      【解决方案2】:

      这是一个例子。

      <!DOCTYPE html>
      <html>
      <body>
      <div>
       <p class="intro">23</p>
       <p class="intro">11</p>
      </div>
      <div>
       <p class="intro">27</p>
       <p class="intro">11</p>
      </div>
      <p id="demo"></p>
      
      <script>
      const x = document.getElementsByClassName("intro");
      for (let i = 0; i < 2; i++) {
       if(x[i].innerHTML == "23"){
        var obj = x[i].parentElement;
       }
      }
      obj.style.backgroundColor  = "red";
      </script>
      
      </body>
      </html>

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-09
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 1970-01-01
      • 2021-10-03
      相关资源
      最近更新 更多