如果包含字符,则为 x,否则为 y (Puppeteer) [英] If contains characters then x, else y (Puppeteer)

查看:52
本文介绍了如果包含字符,则为 x,否则为 y (Puppeteer)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个理论上应该可以工作的代码,但它没有.

I have this code which should work in theory, but it doesn't.

我想它缺少一些东西:

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;

基本上,如果有http"或https"在消息中,上面的代码应该输出一个空消息:

Basically, if there's "http" or "https" in the message, the above code should output an empty message:

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

如果没有检测到这些词,那么它应该正常输出消息:

If none of these words are detected, then it should output the message normally:

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

然而,现在即使消息确实包含http"和https",它仍然返回带有这些词的消息.

However, right now even if the message does contain "http" and "https", it still returns the message with those words.

所以它要么不检测这些词,要么根本不执行 containsWords 过滤器.

So it either doesn't detect these words, or simply doesn't execute containsWords filter at all.

它只是忽略并输出每条消息,而不管我选择的停用词如何.

It simply ignores and outputs every message, regardless of my chosen stop words.

如果有人了解代码并告诉我我在这里遗漏了什么,我将不胜感激.

I would appreciate if someone knowledgable would look into the code and tell me what I'm missing here.

谢谢.

推荐答案

containsWords() 中,您可以将整个消息与每个单词进行比较.要检查消息是否包含任何单词,您需要这样的东西:

In containsWords() you compare the entire message with each word. To check if the message contains any word, you need something like this:

function containsWords(words, message) {
    return words.some(w => message.includes(w));
}

这篇关于如果包含字符,则为 x,否则为 y (Puppeteer)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆