【问题标题】:Trying to find a way to automate when id is the same试图找到一种在 id 相同时实现自动化的方法
【发布时间】:2018-01-23 21:11:01
【问题描述】:

我很难尝试使用 Java (Chrome) 在 Selenium WebDriver 上自动化三个具有相同输入 ID 的文本字段。以下是链接的网站信息。

抄送

<input
    id="recurly-hosted-field-input"
    type="tel"
    pattern="[0-9]*"
    spellcheck="false"
    autocapitalize="none"
    autocorrect="off"
    class="recurly-hosted-field-input unknown"
    placeholder="Credit Card Number"
    title="Credit Card Number"
    aria-required="true"
    autocomplete="cc-number"
    style="visibility: visible; color: rgb(51, 51, 51); font-family: Lato, sans-serif; font-feature-settings: normal; font-kerning: auto; font-size: 17px; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; text-rendering: auto; text-shadow: none; text-transform: none;"
>

月份

<input
    id="recurly-hosted-field-input"
    type="tel"
    pattern="[0-9]*"
    spellcheck="false"
    autocapitalize="none"
    autocorrect="off"
    class="recurly-hosted-field-input"
    placeholder="Month (mm)"
    title="Month (mm)"
    maxlength="2"
    aria-required="true"
    autocomplete="cc-exp-month"
    style="visibility: visible; color: rgb(51, 51, 51); font-family: Lato, sans-serif; font-feature-settings: normal; font-kerning: auto; font-size: 17px; font-stretch: normal; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; text-rendering: auto; text-shadow: none; text-transform: none;"
>

这是我目前使用的格式。

driver.findElement(By.name("address1")).sendKeys("213 Ave");
    driver.findElement(By.name("city")).sendKeys("New York");

【问题讨论】:

    标签: java google-chrome selenium


    【解决方案1】:

    在这种情况下,您有一个 ID,但它在页面上不是唯一的,因为两个 INPUTs 具有相同的 ID。我要做的是开始查看INPUTs 的不同属性,并希望能找到一些独特的东西。在这种情况下,我会假设 title 在页面上是唯一的,并且会从那里开始。

    input[title='Credit Card Number']
    input[title='Month (mm)']
    

    这些都是 CSS 选择器,它们指定了一个 INPUT 标记,其中列出了您列出的两个标记的属性。

    【讨论】:

      【解决方案2】:

      当代码中存在一个不唯一的 ID 时,这被认为是不可能的,因为编程错误,您应该:

      第一个选项:使用另一个不被元素共享的字段

      第二个选项:使用 findElements(By by) 选项以获得可以迭代的列表。在该列表中,您可以查看对象的其他参数是否是您要查找的参数,然后在其上执行您的代码。

      此外,在您的代码中,您正在搜索 By.name,但您的 xml 中没有名称标签。尝试使用 ID,然后像 @RKelley 告诉你的那样,使用刹车 [] 选择你想要的元素。对那个解释清楚和详尽的答案给予积极的价值,就像正确的答案一样。 :)

      【讨论】:

        【解决方案3】:

        您可以使用 Xpath 选择器来定位相似的字段。 我假设它们在单个 div 或任何其他标签中,那么您可以像

        一样访问
        /<path_to_div>/input[0] -->will locate first
        similiarly /<path_to_div>/input[1] -->will locate second abd so on..
        

        您可以从这里获得参考:https://www.guru99.com/xpath-selenium.html

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-06-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-29
          • 1970-01-01
          • 1970-01-01
          • 2021-06-05
          相关资源
          最近更新 更多