How to click a link using link text in nightwatch.js

谁说我不能喝 提交于 2019-12-05 20:28:35

问题


Say I have these elements on my web page.

<a href="/dynamic1">One</a> 
<a href="/dynamic2">Two</a> 
<a href="/dynamic3">Three</a>

I want to click on the link with text Two. How to identify or click that element using the Link Text without any unique attributes like id or class.

In .Net I can use driver.findElement(By.linkText("Images")).click();. What is the equivalent in nightwatch.js


回答1:


The locator By.linkText uses an XPath internally.

So to click the second link from your example with an XPath :

.useXpath()     // every selector now must be XPath
.click("//a[text()='Two']")
.useCss()      // we're back to CSS now

Note that depending on the inner HTML, you may need to concatenate the children and trim the spaces:

.click("//a[normalize-space()='Some link']")



回答2:


The first param to elements() method is the locator strategy, use link text - it is supported:

client
  .url('http://website.org')
  .waitForElementVisible('body', 1000)
  .elements('link text', 'Two', function (result) {

    for (var i = 0; i < result.value.length; i++) {
      var element = result.value[i];

      // do something
    }
  })
  .end();



回答3:


The only way that worked for me was using:

.useXpath()
.click("//*[contains(text(), 'Two')]")
.useCss()      



回答4:


There is a better way now, you can use any of the documented locator strategies. Specifically id, css selector, link text, partial link text, tag name, xpath.)

browser
  .click('link text', 'Some Link Text');


来源:https://stackoverflow.com/questions/38538409/how-to-click-a-link-using-link-text-in-nightwatch-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!