You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nightwatch中如何选中当前元素的内部元素并获取文本?

How to Retrieve Inner Element Text in Nightwatch

Hey there! As a Nightwatch newbie, grabbing text from nested elements is a super common task—let’s walk through straightforward, reliable ways to pull those text values from your specific HTML structure.

Approach 1: Callback-Based CSS Selector Method (Great for Older Nightwatch Versions)

We’ll directly target the <div> elements inside each <a> under <li>, then loop through the matches to extract text:

browser.elements('css selector', '.mywrapperhere ul li a div', function(elementResult) {
  // Iterate over every matched element
  elementResult.value.forEach(function(element) {
    // Fetch text using the element's unique ID
    browser.elementIdText(element.ELEMENT, function(textResult) {
      console.log('Retrieved text:', textResult.value);
      // You can store this text in a variable or run assertions here
    });
  });
});

Approach 2: Modern Promise-Based Syntax (Nightwatch v2+)

If you’re using Nightwatch 2.0 or later, you can use cleaner promise chaining to get an array of all text values in one go:

browser
  // Locate all target div elements
  .findElements('css selector', '.mywrapperhere ul li a div')
  // Map each element to its text content using promises
  .then(elements => Promise.all(elements.map(el => el.getText())))
  // Work with the collected text array
  .then(texts => {
    console.log('All text values:', texts);
    // texts will be: ['text to retrieve', 'text to retrieve 2']
    // Example assertion: expect(texts[1]).to.equal('text to retrieve 2')
  });

Approach 3: XPath Selectors (For Flexible Nested Targeting)

If you prefer XPath (or need it for more complex element paths), this method works just as effectively:

browser.elements('xpath', "//div[@class='mywrapperhere']//ul//li//a//div", function(elementResult) {
  elementResult.value.forEach(function(element) {
    browser.elementIdText(element.ELEMENT, function(textResult) {
      console.log('Text via XPath:', textResult.value);
    });
  });
});

Quick Tip

If your <a> tags only contain that single text-bearing <div>, you could also target the <a> elements directly (.mywrapperhere ul li a) and grab their text. But targeting the <div> ensures you only get the exact text you need, even if extra elements are added to the <a> later.

内容的提问来源于stack exchange,提问作者adrive

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:49:07