【发布时间】: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
如何在 Nightwatch 中点击href 链接?
href 文本彼此相同,所以我不能使用 XPath 文本。
我试过了:
browser.useXpath().click("//a[href='./basket/removeItem.html?id=5de6710f75a5750f3d88495b')]");
但这不起作用。
【问题讨论】:
标签: html xml xpath href nightwatch
至少,更正您的 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 伪元素。答案已更新到地址。
您可以使用 XPath 中的索引来选择第一个或第二个链接。
对于第一个链接:
//a[@id='tst_remove_from_basket'][1]
第二个链接:
//a[@id='tst_remove_from_basket'][2]
【讨论】:
browser.useXpath().click("a[@id='tst_remove_from_basket'][1]"); 因为那不起作用