Warm tip: This article is reproduced from serverfault.com, please click

javascript-如果.textContent包含X,则单击

(javascript - If .textContent contains X then click)

发布于 2020-11-29 23:30:06

我想点击我的gmail收件箱(首页收件箱)中包含/开头为“安全”一词的每封电子邮件(例如,它将点击以下电子邮件)

<span id=":31" class="bog">
<span class="bqe"">
Security alert - please check here
</span>
</span>
</pre>

我的收件箱中有50个.bog元素(电子邮件预览的主题行)。

我想找到这50个元素中的哪个包含“安全性”,然后单击它们。它可能包含其他词。

我试过了:

const elements = await page.$$(".bog");
var text = await page.evaluate(() => document.querySelector('.bog').textContent);
console.log(text);
if (text.textContent === "Security") {
    text.click();
} else {
    console.log("NO")
}
    const elements = await page.$$(".bog");
    const emails = Array.from(elements);
    emails.forEach((email) => {
        if (email.textContent === 'Security alert') {
           email.click();
           console.log("found");
        }
    })

await page.$$eval('.bog', elements => {
    const element = elements.find(element => element.innerHTML === 'Security alert');
    element.click();
});
emails.forEach((email) => {
   if (email.textContent === 'Security alert') {
      email.click();
      console.log("found");
   }
    console.log(email.textContent)
})

但我真的不知道该怎么办-会希望得到一些指导。所有这些给了我各种各样的错误,但是当我尝试执行X.textContent时,我经常得到未定义的错误吗?

让我知道我是否应该提供更多信息。

谢谢!

Questioner
Dave
Viewed
0
10.4k 2020-12-09 07:08:34

使用时,你将document.querySelector(".cssSelector")获取与该CSS选择器相对应的第一个元素,而不是所有元素都将被获取。要获取所有元素,可以使用document.querySelectorAll(),它返回所有元素NodeListArray-Like)列表。

然后,为了在element.textElement中搜索特定的子字符串,可以使用各种字符串内置方法甚至正则表达式。Yuo可以使用for循环,forEach,Array.prototype.filter,这里的天空是极限。

由于你对子字符串“ Security”的索引位置(以它开头的单词,单词的中间,哪里?)的索引位置不太清楚String.prototype.indexOf()String.prototype.includes因此可以使用依此类推。

用例:

const nodeBogs = document.querySelectorAll(".bogs");
nodeBogs.forEach(elem => {
  if (elem.textContent.includes("Security") {
  // do your things here
});

你也可以使用Array.prototype.filter

const nodeBogs = document.querySelectorAll(".bogs");
const filteredElems = [...nodeBogs].filter(elem => elem.textContent.includes("Security"));

// now you have an Array of filtered elements that contain the word "Security"

这些用例确实是冰山一角。你可以通过多种不同方式解决此简单问题。查阅Mozilla文档,熟悉JS内置方法和该语言的语法。然后,你就在旅途的开始,尽可能多地测试你的程序。使用console.logs(文本编辑器内置调试器)可以帮助你了解错误的位置或代码的行为的任何内容。