【问题标题】:What are the best practices for using custom automation ids in Selenium WebDriver在 Selenium WebDriver 中使用自定义自动化 ID 的最佳实践是什么
【发布时间】:2021-02-03 18:03:28
【问题描述】:

我们的 Web UI 为每个元素(按钮、标签等)提供了唯一的自定义自动化 ID。我无法访问元素的正常 ID。

<button custom-id='send' class='dynamic_class_123'>

如何以最佳实践方式访问元素? 现在我使用以下定位器

@FindBy(xpath = "//button[@custom-id='send']")
public WebElement sendButton;

一旦开发人员将按钮转换为 div 元素,自动化代码就会中断。 正常的 id 不会有这个问题:

@FindBy(id = "send")
public WebElement sendButton;

无论类型如何(按钮、跨度、div、...),它都会找到元素。

有没有一种方法可以在不需要 xpath 或至少改进版本的情况下使用我的自定义 id 实现相同的结果?

【问题讨论】:

    标签: java selenium selenium-webdriver xpath automated-tests


    【解决方案1】:

    您可以使用不带标签的选择器,以下是示例:

    css = "[custom-id='send']"
    xpath = "//*[@custom-id='send']"
    

    【讨论】:

      【解决方案2】:

      有几点:

      您访问该元素的代码块:

      <button custom-id='send' class='dynamic_class_123'>
      

      看起来很完美,因为custom-ids 总是独一无二的。


      现在,开发团队突然无法将&lt;button&gt; 元素转换为&lt;div&gt; 元素:

      • 一般情况下,&lt;button&gt; 元素默认配置为可交互
      • 默认情况下&lt;div&gt; 元素不可交互,除非contenteditable 属性设置为true

      结论

      无论&lt;tagName&gt;&lt;button&gt;&lt;div&gt; 还是&lt;span&gt; 无关,如果应用程序为所需元素生成唯一的custom-id,您可以通过它们各自的custom-id 继续识别这些元素如下:

      • 使用css

        @FindBy(xpath = "[custom-id='send']")
        public WebElement sendButton;
        
      • 使用xpath

        @FindBy(xpath = "//*[@custom-id='send']")
        public WebElement sendButton;
        

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多