【问题标题】:Click on XPath-selected href link in Nightwatch? [duplicate]在 Nightwatch 中单击 XPath 选择的 href 链接? [复制]
【发布时间】:2020-03-28 07:51:37
【问题描述】:

如何在 Nightwatch 中点击href 链接?

href 文本彼此相同,所以我不能使用 XPath 文本。

我试过了:

browser.useXpath().click("//a[href='./basket/removeItem.html?id=5de6710f75a5750f3d88495b')]");

但这不起作用。

【问题讨论】:

    标签: html xml xpath href nightwatch


    【解决方案1】:

    至少,更正您的 XPath 以在 href 前面添加 @ 属性 并删除虚假的 )

    //a[@href='./basket/removeItem.html?id=5de6710f75a5750f3d88495b')]
        ^add                                                        ^delete
    

    如果id 变体有问题,请通过starts-with() 排除它:

    //a[starts-with(@href, './basket/removeItem.html')]
    

    如果页面上有多个这样的@href属性,您可以通过索引选择一个(如shown by @Christine,+1):

    //a[starts-with(@href, './basket/removeItem.html')][1]
    

    实际问题

    OP 添加了一个指向 HTML 图像(呃)的链接,该链接显示目标 a 链接在文档中,因为 ::before CSS pseudo element。在这种情况下,该元素实际上并不存在于要像往常一样选择的 DOM 中。

    另见:

    【讨论】:

    • NoSuchElementError: An error occurred while running .click() command on <a[@href='./basket/removeItem.html?id=5de6710f75a5750f3d88495b']>: 我试图得到的部分看起来像这样link。顺便说一句,ID 是唯一的(在 href 之后,tst_remove_from_basket 与每个删除项相同)
    • 如果 href 中的 id 是唯一的,那么使用 starts-with() 的 XPath 似乎应该处理这种情况。
    • Error while running .locateMultipleElements() protocol action: invalid selector: Unable to locate an element with the xpath expression a[starts-with(@href, './basket/removeItem.html?id=5de6710f75a5750f3d88495b') because of the following error: NoSuchElementError: An error occurred while running .click() command on <a[starts-with(@href, './basket/removeItem.html?id=5de6710f75a5750f3d88495b')>:
    • 问题是由于::before 伪元素。答案已更新到地址。
    • 感谢您的帮助。也许这会起作用,但这确实不适合我的项目。对于 HTML 图像的帖子,我深表歉意。
    【解决方案2】:

    您可以使用 XPath 中的索引来选择第一个或第二个链接。

    对于第一个链接:

    //a[@id='tst_remove_from_basket'][1]
    

    第二个链接:

    //a[@id='tst_remove_from_basket'][2]
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 2016-11-13
    • 2014-04-10
    • 2016-11-14
    • 1970-01-01
    • 2018-04-23
    • 2017-03-19
    相关资源
    最近更新 更多