【问题标题】:How to distinguish between two WebElements with the same id?如何区分具有相同 id 的两个 WebElement?
【发布时间】:2019-10-15 04:09:21
【问题描述】:

我在一个 HTML 页面上有两个具有相同 id 的字段(使用 Angular) 如何在不创建集合和引用索引的情况下区分两者>

下面是一个字段的示例

我试过了

#content-container > inv-sidebar-layout-content > ng-component > ng-component > section > div.row.tab-container > as-split > as-split-area:nth-child(1) > article > inv-people-tabs > inv-vertical-tabs-list > div.tab-content-container > div > inv-tab:nth-child(7) > div > inv-people-contact-details-tab > section > div.left-column > inv-person-contact-details > section > inv-address-edit > section > div:nth-child(2) > input

但是太长太麻烦了

第一个字段的 HTML 是

<input _ngcontent-gec-c113="" class="inv-input" id="towncity" formcontrolname="TownCity">

第二个是

<input _ngcontent-gec-c113="" class="inv-input ng-pristine ng-valid ng-touched" id="towncity" formcontrolname="TownCity" ng-reflect-name="TownCity">

【问题讨论】:

  • 你应该想办法让每个idunique.
  • @ConnorsFan 如果您拥有该网站或可以倡导该修复,那很好,但有些人没有这个选项。
  • 需要更多关于这两个元素的上下文。为什么同一个 TownCity 元素会在页面上出现两次?是桌面版还是移动版?难道是两种不同的形式,各有各的吗?您需要在祖先中找到一个不同的元素(最好带有 ID)并使用它来区分它们,例如#mobile #towncity#desktop #towncity.
  • 同意@ConnorsFan 100%。该网站目前不是符合 W3C 的 HTML,应该已修复。

标签: c# angular selenium-webdriver xpath css-selectors


【解决方案1】:

元素具有不同的类,因此您可以使用class attribute 区分它们

示例选择器:

  1. 第一个元素:

    //input[@id='towncity' and not(contains(@class,'touched'))]
    

  2. 第二个元素

    //input[@id='towncity' and contains(@class,'touched')]
    

更多信息:

【讨论】:

  • 一般来说,是的,但我猜这些类正在跟踪状态,因此它们可能会出现/消失,并使元素定位器无法找到它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 1970-01-01
  • 1970-01-01
  • 2020-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多