【问题标题】:How to fetch these input fields with dynamic ids如何使用动态 id 获取这些输入字段
【发布时间】:2012-06-30 18:06:31
【问题描述】:

我有一个网页,其中很少有文本字段需要使用 Selenium WebDriver 填充一些值。但我无法使用 selenium 框架中提供的 API 获取这些项目,因为 ID 是动态变化的。

例如,其中一个文本字段具有以下 ID

<input id="order_unit_line_rate_806099_unit_price" type="text" value="" uniqueattr="Dynamic Site Accelerator / Dynamic Site Accelerator / Platform Fee / / Price" size="10" onchange="javascript:numberFormatValid('order_unit_line_rate_806099_unit_price', parseI18nNumber($('order_unit_line_rate_806099_unit_price').value, ',', '.'), 5, '.');" name="order_unit_line_rate[806099][unit_price]">

其中作为 id 一部分的数字 806099 对于每个新页面和每个新文本框都会有所不同。使用 findElements(By.id()) API 我没有任何运气。

有人可以建议任何方法来识别这些元素。

我使用eclipse作为编辑器,java作为客户端驱动,selenium webDriver作为自动化框架。

谢谢 基兰

【问题讨论】:

  • 当我尝试使用 findElement.(By.name());因为名称还包含 6 位数字。 \n 无论如何我可以在这里使用正则表达式。 ?

标签: java selenium-ide selenium-firefoxdriver


【解决方案1】:

您可以使用 findElementsByTagName 然后遍历每个返回的元素,检查其 ID 与您的正则表达式:

public static WebElement findElementByRegexId(FindsByTagName ctx, String tagName, String regex) {
    List<WebElement> l = ctx.findElementsByTagName(tagName);
    for (WebElement e : l) {
        if (e.getAttribute("id").matches(regex)) {
            return e;
        }
    }
    return null;
}

【讨论】:

  • 感谢您的回复 :) .. 将尝试此操作并就观察结果回复您 :)
  • 那是我正在寻找的完美答案。感谢一百万的回复:)。
【解决方案2】:

selenium API 还允许您传递 XPath 定位器,因此您可以尝试类似的方法

findElements(By.xpath("//input[@uniqueattr=\"Dynamic Site Accelerator / Dynamic Site Accelerator / Platform Fee / / Price\"]"));

更多详情请见here

【讨论】:

  • @Didlier : 感谢好友的回复 :) .. 将尝试这个并就观察结果回复您 :)
  • @Didler :这是我使用它时遇到的错误。 org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//input[@uniqueattr=\"动态站点加速器/动态站点加速器/平台费用//价格\ "]"}
  • 我刚刚在 Selenium IDE 中尝试过,它似乎可以工作,尝试做同样的事情来验证提议的 XPath。此外,您应该注意引号和转义。也许您可以尝试使用这样的单引号:findElements(By.xpath("//input[@uniqueattr='Dynamic Site Accelerator / Dynamic Site Accelerator / Platform Fee / / Price']"));。这种 XPath(包含用户友好的标签)的问题在于它非常容易出错。不能添加技术属性,或者使用类属性吗?也许问题在于uniqueattr 不是标准属性。
  • 你说得对,@unique 不是标准属性,它是我们的开发团队自定义添加的属性,我发现没有 API 可以对其执行 get() :( ..
【解决方案3】:

您可以使用以下解决方案,而不是使用正则表达式

//input[contains(@name, 'order_unit_line_rate')] 

【讨论】:

  • @Thanks Rohit,但还有更多具有相同起始字符串的元素,例如复选框。我需要填充的文本框的名称为 "order_unit_line_rate[806099][unit_price]" 或 "order_unit_line_rate[806099][limit_price]" 。所以我需要检查 6 位数字后面的那部分字符串。任何关于此的cmets
  • 您可以使用 unit_price 或 limit_Price 文本。这对您有用吗??
  • 我尝试了所有这些 Rohit,:( 但是几天都找不到定位器 :(。我也尝试了 @uniqueattr 的语法,但又没有运气了 :( .. 还有更多建议吗?跨度>
猜你喜欢
  • 1970-01-01
  • 2018-02-21
  • 1970-01-01
  • 1970-01-01
  • 2017-11-28
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
  • 1970-01-01
相关资源
最近更新 更多