【问题标题】:Fastest way to select an option using selenium?使用硒选择选项的最快方法?
【发布时间】:2013-11-21 00:19:52
【问题描述】:

我有一个 UI 测试在一个下拉列表中失败,其中包含很多选项(超过 1000 个)。错误消息是“对 URL 的远程 WebDriver 服务器的 HTTP 请求...在 60 秒后超时”。

现在我承认在下拉菜单中包含这么多选项并不是一个好习惯,但我目前无法更改。话虽如此,使用 Selenium 通过文本选择选项的最快方法是什么?我可以使用 xpath 获得任何速度来查找选项,还是有其他方法可以做到这一点?谢谢。

这是我当前的代码:

            var fieldElement = driver.FindElement(dropDownLocator);
            var select = new SelectElement(fieldElement);
            select.SelectByText(value);

【问题讨论】:

  • 我的理解是 xpath 比 Selenium 中的 CSS 慢得多。对于这样大小的下拉列表,您可能需要考虑使用 javascript 执行器方法。可能您可以使用一种方法来选择要单击的特定选项,而不是 SelectElement 方法。
  • 在这一切之下,SelectElement 使用 XPath 来查找 select 的子 option 元素。究竟什么是慢?最初找到select 或选择optiontext
  • Arran - 查找选择很快,但根据其文本选择特定选项是缓慢且超时的部分。

标签: c# testing xpath selenium selenium-webdriver


【解决方案1】:

这就是我最终要做的。我使用 IJavaScriptExecutor 并编写了一个脚本来查找具有特定文本的列表中的第一个选项。这个解决方案并不完美,如果在我的测试中我选择列表底部的一个选项,它可能仍然会超时。在我的情况下,该选项根本不会影响功能,因此我可以在列表顶部附近选择一个选项,它会很快找到它。

var fieldElement = driver.FindElement(dropDownLocator);                       
var js = (IJavaScriptExecutor)driver;
var script = string.Format("$('#{0} option').each(function (){{if($(this).text() == \"{1}\"){{$(this).attr('selected', true);return false;}}}});", fieldElement.GetAttribute("id"), value);
js.ExecuteScript(script);

【讨论】:

  • 哇,感谢这个糟糕的解决方案。通过使用script 而不是SelectElement,我能够将运行时间从6 分钟缩短到15 秒。打算远离SelectElement
【解决方案2】:

根据我的理解(和实践),使用 id 是与 Selenium 中的选择器交互的最快方式。以下是我在自动化代码中使用的一些示例选择器:

@FindBy(css = "p.productSKU") protected WebElement skuVal;
@FindBy(id="sku") protected WebElement sku; 
@FindBy(className = "reducedPrice") protected List<WebElement> reducedPrice;

不过,Selenium 中的 FindBy Interface 将允许您使用以下内容:

id, xpath, using, css, name, className, tabName, linkText, and partialLinkText

我个人更喜欢使用 id 和 xpath。但是,根据您要自动化的内容以及它是/如何开发的,其他机制也可能变得必要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多