簡體   English   中英

提取網頁中的字數

[英]Fetching word count in a web page

這肯定是一個非常籠統的問題,但是我沒有遇到任何具體或穩定的解決方案。

我只想獲取網頁中所有瀏覽器中的單詞數。 我當前的實現是

var body = top.document.body;
if(body) {
    var content = body.innerText || body.textContent;
    content = content.replace(/\n/ig,' ');
    content = content.replace(/\s+/gi,' ');
    content = content.replace(/(^\s|\s$)/gi,'');
    if(!body.innerText) {
        content = content.replace(/<script/gi,'');
    }
    console.log(content);
    console.log(content.split(' ').length);
}

這很好用,但不適用於某些Firefox瀏覽器,因為innerText在Firefox上不起作用。

如果我使用textContent,那么它也會顯示JS標簽的內容(如果存在)。 例如,網頁內容是否為

<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript"> 
    console.log('Hellow World');
    var some = "some";
    var two = "two";
    var three = "three";
    </script>

    <h1 style="text-align:center">Static content from Nginx</h1>
    <div>
        This is a 
            static.
            <div>
                This is a 
                    static.
            </div>
    </div>
</body>

然后,textContent的內容中也會包含JS代碼,這會給我帶來錯誤的字數統計。

什么是可以在任何環境下工作的具體解決方案。

PS:沒有JQuery

好的,您有兩個問題:

跨瀏覽器innerText

我會去:

var text = document.body[('innerText' in document.body) ? 'innerText' : 'textContent'];

那樣,寧願使用innerText而不是textContent。

<script>標簽的剝離結果。

dandavis為此提供了一個簡潔的解決方案:

function noscript(strCode){
    var html = $(strCode.bold()); 
    html.find('script').remove();
    return html.html();
}

和非jQuery解決方案:

function noscript(strCode){
    return strCode.replace(/<script.*?>.*?<\/script>/igm, '')
}

該函數會將字符串轉換為“偽造”的html文檔,剝離其腳本標簽並返回原始結果。

當然,您可以改善功能,以同時刪除<style>標記和其他標記。

盤點字母

您的工作方法還不錯,但是我仍然認為,簡單的正則表達式會做得更好。 您可以使用以下方法計算字符串中的單詞:

str.match(/\S+/g).length;

最后

最終結果應該像

var body = top.document.body;
if(body) {
    var content = document.body[('innerText' in document.body) ? 'innerText' : 'textContent'];
    content = noscript(content);
    alert(content.match(/\S+/g).length);
}

隱藏/不可見/覆蓋的塊呢? 您是否想在其中全部計算單詞? 圖像呢(圖像的alt標簽)

如果要全部計數-只需剝離標簽並計數所有其余塊的測試。 像這樣的$('body:not(script)')。text()

非常感謝您提供如此有用的答案。 如果未在瀏覽器中定義innerText,我發現可以使用這種方法。 而且我們得到的結果與innerText非常相似。 因此,我認為在所有瀏覽器中都將保持一致。

大家請仔細研究一下,讓我知道這個答案是否可以接受。 並且讓我知道你們是否在我使用的這種方法中發現任何差異。

function getWordCount() {
    try {
        var body = top.document.querySelector("body");
        if (body) {
            var content = body.innerText || getInnerText(top.document.body, top);
            content = content.replace(/\n/ig, ' ');
            var wordCount = content.match(/\S+/gi).length;
            return wordCount;
        }
    } catch (e) {
        processError("getWordCount", e);
    }
}


function getInnerText(el, win) {
    try {
        win = win || window;
        var doc = win.document,
            sel, range, prevRange, selString;
        if (win.getSelection && doc.createRange) {
            sel = win.getSelection();
            if (sel.rangeCount) {
                prevRange = sel.getRangeAt(0);
            }
            range = doc.createRange();
            range.selectNodeContents(el);
            sel.removeAllRanges();
            sel.addRange(range);
            selString = sel.toString();
            sel.removeAllRanges();
            prevRange && sel.addRange(prevRange);
        } else if (doc.body.createTextRange) {
            range = doc.body.createTextRange();
            range.moveToElementText(el);
            range.select();
        }
        return selString;
    } catch (e) {
        processError('getInnerText', e);
    }
}

我得到的結果與innerText相同,並且比使用正則表達式或刪除標簽等更為准確。

請給我您的意見。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM