有什么方法可以过滤 html 文档的数据吗?

Is there any way to filter data of an html document?

我目前正在开发一个 chrome 扩展程序,它使用网站的 html 文档来提取数据,但我需要制作一个过滤器来获得我真正想要的内容。

在这次尝试中,扩展程序获取页面的 HTML 并将其转换为字符串以便于操作:

//This method gets a string and counts how many times
//the word you're looking for its in the string
function countWordInAString(string, word) {
    return (string.match(new RegExp(word, "g")) || []).length;
}

function getOutlookData(html) {
    var unreaded = countWordInAString(html, 'no leídos');
    var readed = countWordInAString(html, 'leídos');
    var totalMails = countWordInAString(html, 'id="AQAAA1thnTQBAAAEA7R1mgAAAAA="');
    var message = totalMails + 'Mails loaded! \n Mails readed: ' + readed + '\n Mails unreaded: ' + unreaded;

    return message + '\n' + "HTML:\n" + html;
}

它在某些特定情况下有效,但对于混淆网站(如本例中的 outlook),结果是错误的。我可以做些什么来改进它?

您的 'word' 可能包含特殊字符。 传递给您的正则表达式时用反斜杠对其进行编码 即

const encodeForReg = str => str.replace(/([^\s\w])/g, '\');
function countWordInAString(string, word) {
    const encodedWord = encodeForReg(word);
    return (string.match(new RegExp(encodedWord, "g")) || []).length;
}
id="AQAAA1thnTQBAAAEA7R1mgAAAAA="

变成

id\=\"AQAAA1thnTQBAAAEA7R1mgAAAAA\=\"