【问题标题】:Protractor, how to get an element if others classes have the same classname量角器,如果其他类具有相同的类名,如何获取元素
【发布时间】:2018-11-15 00:41:26
【问题描述】:

我在测试中使用 Protractor 和 Cucumber,但我无法获取元素,因为类名与其他类相同,并且没有其他属性。 我怎样才能得到这个元素? 元素是:“tileGrid 内容”。 我无法使用 xpath,因为有时会编辑页面。

这是我的html:

<div class="tileGrid content">
  <div class="spacing-container undefined">
    <div class="title">
      <h3 class="h2 heading">External Services</h3>
    </div>
  </div>
</div>

感谢您的帮助。

【问题讨论】:

  • 请在您的问题中发布相关的html和js代码sn-ps。不鼓励在 SO 中使用外部链接和图像中的代码。
  • 您好 AndrewL,感谢您的回答。我没有 js,因为我不知道如何“仅”使用这个元素。它没有其他属性,只有“类”。我可以做类似“element(by.css('tileGrid.content'));”的事情但是这样我把所有这个类名的元素都取了,还有很多。
  • 实际上,您刚刚在上面的评论中发布的代码 sn-p 只会抓取第一个匹配的元素。您需要使用element.all() 来获取所有这些。您需要有关此元素的更具体的内容吗?为什么是这个?
  • 您好,tehbeardedone,谢谢您的回答。我必须检查是否存在此特定元素,原因是页面中组件的容器,并且在功能文件中写入我必须检查此元素是否存在。在 element.all() 之后,我怎样才能得到这个特定的元素? div 标签上没有包含容器的其他属性,所以我不知道如何具体说明这一点。在普通的 javascript 中,我使用 document.getElementsByClassname('tileGrid Container')[0] 或类似“children”或“childNodes”的东西来执行此操作。
  • 澄清一下,您是否只需要检查带有文本外部服务的标题是否存在?或者还有其他您正在寻找的东西吗?如果您要查找其他内容,则可以获取所有元素,然后按您要查找的内容进行过滤。例如,使用您在上面发布的 html sn-p,您可以获得类 titleGrid 的所有 div,然后按元素的文本过滤以找到包含 External Services 的那个并返回,这样您就知道它是正确的元素.

标签: javascript protractor cucumber classname


【解决方案1】:

我想你的结构类似于:

<div>
  <div class="tileGrid content">
    <div class="spacing-container undefined">
      <div class="title">
        <h3 class="h2 heading">External Services</h3>
      </div>
    </div>
  </div>
  <div class="tileGrid content">
    <div class="spacing-container undefined">
      <div class="title">
        <h3 class="h2 heading">Other Header</h3>
      </div>
    </div>
  </div>
  <div class="tileGrid content">
    <div class="spacing-container undefined">
      <div class="title">
        <h3 class="h2 heading">Another Header</h3>
      </div>
    </div>
  </div>
 ...
</div>

您可以通过多种方式与这样的东西进行交互,但我将仅举 3 个示例:

这将在其父级中查找第一个带有 div 标签的子级

by.css('div div.content:nth-of-type(1)') 

这将在其父级中查找具有任何标签的第一个子级

by.css('div div.content:nth-child(1)')

这将寻找h3标签内的文本,并选择它上面3层的元素:

by.xpath('//*/h3[text()="External Services"]/../../..')

或者找到一个DIV,其中包括一个H3,而H3的文本是External Services,如下所示:

by.xpath('//div[contains(@class, "tileGrid")][.//h3[text()="External Services"]]')

【讨论】:

  • 我在上面添加了一个定位器by.xpath('//div[contains(@class, "tileGrid")][.//h3[text()="External Services"]]'),请尝试一下,看看它是否有效,并且可以满足未来的页面变化。
猜你喜欢
  • 1970-01-01
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
相关资源
最近更新 更多