【问题标题】:How to write a CSS locator for a button如何为按钮编写 CSS 定位器
【发布时间】:2014-12-20 14:55:50
【问题描述】:
<div class="test" data-credit-card-index="1">

    <button class="test1 test">Delete</button>
    <button class="test1 test">Edit</button>

我想为“编辑”按钮编写一个 CSS 定位器。它位于 [data-credit-card-index="1"] 部分下...那里会有更多信用卡...所以我必须使用 [data-credit-card-index="1"] 加上 Edit 来定位我的定位器。

有人可以帮忙吗?非常感谢!!

【问题讨论】:

    标签: css selenium


    【解决方案1】:

    更新

    对于硒:

    By.cssSelector('.test[data-credit-card-index="1"] button.test:eq(1)')
    

    或者使用 XPath:

    By.xpath('div[@data-credit-card-index="1"]/button[contains(text(),"Edit")]')
    

    原始答案(jQuery)

    第一:

    $('.test[data-credit-card-index="1"] button:contains("Edit")');
    

    第二:

    $('.test[data-credit-card-index="1"] button.test:eq(1)');
    

    但如果允许,最好使用附加类:

    <div class="test" data-credit-card-index="1">
    
        <button class="test1 test delete-button">Delete</button>
        <button class="test1 test edit-button">Edit</button>
    

    和:

    $('.test[data-credit-card-index="1"] .edit-button');
    

    【讨论】:

    • 不会对此投反对票,因为在给定上下文(Selenium)的情况下,您确实给出了正确的答案,但您的第一个答案不是(contains 不是 CSS 选择器标准的一部分。)跨度>
    • 抱歉,由于 cforcloud 的基于 jQuery 的答案,我错过了上下文。
    【解决方案2】:

    对于 jquery,你可以使用:contains,比如

    $("button:contains('Edit')")
    // or
    $('[data-credit-card-index="1"]').find("button:contains('Edit')")
    

    【讨论】:

    • 我正在写 selenium 自动化, ('[data-credit-card-index="1"]').find("button:contains('Edit')") 看起来不行对我来说
    • 看起来 selenium 在 :contains stackoverflow.com/questions/14595149/… 方面存在问题。按照上面的建议尝试 :eq(1) 。但实际上它应该由 selenium docs 工作
    • contains 不适用于 Selenium,因为 contains 不是 CSS 选择器标准的一部分。只是 jQuery(更确切地说,它是支持选择器引擎,Sizzle)实现了他们自己的版本。所以这个答案对于 jQuery 选择器(不是 CSS 选择器)是正确的,但在 Selenium 的上下文中是不正确的。
    猜你喜欢
    • 1970-01-01
    • 2019-09-05
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多