简体   繁体   English

我可以在nightwatch.js中按其数组位置选择一个元素吗?

[英]Can I select an element by its array position in nightwatch.js?

I am looking to automate some of my testing processes and I am relatively new to Nightwatch.js and javascript. 我希望自动化我的一些测试过程,我对Nightwatch.js和javascript相对较新。 Is there a way that I can click an element based on it's class and position in the subsequent array that will be returned if there are multiple elements with the same class. 有没有一种方法可以根据它在后续数组中的类和位置单击一个元素,如果有多个具有相同类的元素,将返回该元素。

For example take the following HTML: - 例如,采用以下HTML: -

<div class="clickable-button"><p>Some Text</p></div>
<div class="clickable-button"><p>Some Text 2</p></div>
<div class="clickable-button"><p>Some Text 3</P></div>

If I use chrome development tools and run the following command in the console: - 如果我使用chrome开发工具并在控制台中运行以下命令: -

$('.clickable-button')

It returns an array of the three elements listed above. 它返回上面列出的三个元素的数组。

I would like to click the first <div> element and want to know if there is a way I can do this using a CSS selector? 我想点击第一个<div>元素,想知道我是否有办法使用CSS选择器做到这一点? I cannot select via the text that appears within the <p> tag as this is dynamic data. 我无法通过<p>标签中显示的文本进行选择,因为这是动态数据。

I have tried the following commands in Nightwatch: - 我在Nightwatch中尝试了以下命令: -

browser.click('.clickable-button'[0])

browser.click('clickable-button[0]')

Neither of these options work. 这些选项都不起作用。 Any help or advice would be appreciated. 任何帮助或建议将不胜感激。

You could probably use :nth-of-type 您可以使用:nth-of-type

browser.click('.clickable-button:nth-of-type(1)');

BTW :nth-of-type is part of CSS3 so it is not supported by older browsers. BTW :nth-of-type是CSS3的一部分,因此旧版浏览器不支持它。

Besides using CSS selector, XPath is another option, you can do 除了使用CSS选择器,XPath是另一种选择,你可以做到

browser .useXpath() //ignore this line if you already selected xpath as strategy .click('(//div[@class="clickable-button"])[1]')

to locate the first button. 找到第一个按钮。 Reference 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM