Puppeteer 如果字符串包含 X,则执行此操作,否则执行此操作

Puppeteer if string contains X, then do this, else do this

所以现在我有这段代码可以获取结果并且效果很好:

module.exports = async function grabResult(page) {
  const message = await page.$eval(
    'div > div:nth-child(2)',
    (el) => el.innerText
  );

  const username = await page.$eval(
    'child(15) .username',
    (el) => el.innerText
  );

  return { message, username };
};

console.log(result);

以上代码输出:

{ message: 'message text goes here', username: 'John' }

我想做的是在 return 结果之前,检查 'message' 是否包含某些词。

例如,如果 'message' 包含“http”、“https”,那么它将 return 为空(这正是我需要的):

{ message: '', username: 'John' }

如果它不包含“http”、“https”,那么它将 return 'message' 结果作为我的原始代码。

{ message: 'message text goes here', username: 'John' }

我知道有一个命令可以检查文本是否包含 x。我在另一个线程上找到了这段代码:

if ((await page.waitForXPath('//*[contains(text(), "Subscription Confirmed")]',30000)) !== null) {
   chk = await page.evaluate(el => el.innerText, await page.$x('//*[contains(text(), "Subscription Confirmed")]'))
   chk = 'Success'
} else { 
   chk = 'Failed'
}

但我正在努力将这两者合并为一个代码。

如有任何帮助,我们将不胜感激。

我不是编码员,希望我清楚..

不要太复杂,你可以写一个条件来检查里面存储了什么message。如果您有更多要比较的值,我可以想象这就是您要找的东西:

function containsWords(words, word) {
    return words.filter(w => w === word).length > 0;
}

function grabResult(message, username) {
    return {
        message: containsWords(['http', 'https'], message) ? '' : message,
        username: username
    };
}

它returns:

{ message: '', username: 'pavelsaman' }

当消息等于 httphttps 时。否则它 returns 非空 message 属性.

显然,“包含”的含义也很重要,也许不应该存在严格的相等性,也许您想检查字符串是否以“http”或“https”开头。然后相应地调整它。


包含导出模块的整个文件如下所示:

function containsWords(words, word) {
    return words.filter(w => w === word).length > 0;
}

async function grabResult(page) {
    const message = await page.$eval(
        'div > div:nth-child(2)',
        (el) => el.innerText
    );
    
    const username = await page.$eval(
        'child(15) .username',
        (el) => el.innerText
    );

    return {
        message: containsWords(['http', 'https'], message) ? '' : message,
        username: username
    };
};


module.exports = grabResult;