nodejs cheerio模組提取html頁面內容

來源:互聯網
上載者:User

標籤:orm   otto   special   具體步驟   fit   weight   rds   contain   元素屬性   

nodejs cheerio模組提取html頁面內容Table of Contents
  • 1. nodejs cheerio模組提取html頁面內容
    • 1.1. 找到目標元素
    • 1.2. 美化文本輸出
    • 1.3. 提取答案文本
    • 1.4. 最終代碼

本文給出使用一個用cheerio模組提取html檔案中指定內容的例子,並說明具體步驟、涉及到的API、以及其它模組。 cheerio模組是一個類似jquery的模組,具有相似的API、功能,能夠將一個網頁解析為DOM,以及通過selector選擇元素,設定、擷取元素屬性。

以下為我們待解析網頁:

 

目標是將task1-5中的所有題目、以及答案提取出來,以文本形式儲存。最終提取出的效果如下。 這是題目文本:

Task 1: You will be given 10 minutes to read the text for the first time and then choose an appropriate answer for each of the following questions.1. What’s the passage mainly about?A. How to learn online successfully.B. How to set up a learning goal.C. The future of online learning.D. The benefits of online learning.2. Charles fruitlessly applied for job after job because of the following reasons EXCEPT  ________.A. he lacked in qualifications.B. he had no special training.C. he is too old and can’t walk.D. he wasn’t even able to do office work.3. Weather has great __________ on our health.A. communicative.B. effective.C. student-centered.D. teacher-centered.

這是答案文本:

Task 1:1. D2. C3. C4. D5. A

註:其中答案儲存在網頁中,但在網頁中沒有顯示出來。

1.1 找到目標元素

提取問題文本的整體思路:先找到包含題目的所有元素,然後再擷取這些元素的內容即可。 通過chrome的devtool(或者firefox的firebug)看出,所有的目標元素為:hr元素的所有兄弟結點。cheerio的nextAll函數滿足需求,這個函數擷取當前結點的所有後續的兄弟結點。程式如下:

 
var fs = require(‘fs‘);var cheerio = require(‘cheerio‘);var myHtml = fs.readFileSync("a.html");var $ = cheerio.load(myHtml);var t = $(‘html‘).find(‘hr‘);var t2 = t.nextAll();t2.each(function(i, elem) {    getContent($(this));    console.log($(this).text());});

 

首先將網頁讀取為一個字串,傳給cheerio.load函數,傳回值即是一個cheerio對象(類似於一個jquery對象)。然後使用find函數,通過selector尋找hr元素。再調用 nextAll函數得到hr元素的所有兄弟結點。 最後在each函數中, 通過text函數將所有包含問題的元素的見容列印出來。

結果中有亂碼,問題原因是fs模組不支援中文。通過iconv-lite先解碼為中文解決。修改後代碼如下:

var fs = require(‘fs‘);var cheerio = require(‘cheerio‘);var iconv = require(‘iconv-lite‘);  var myHtml = fs.readFileSync("a.html");var $ = cheerio.load(iconv.decode(myHtml, ‘gbk‘));var t = $(‘html‘).find(‘hr‘);var t2 = t.nextAll();t2.each(function(i, elem) {    getContent($(this));    console.log($(this).text());});

 

最終結果如下:

           Task  1: You will be given 10 minutes to read the text for the first time and then                                          choose  an appropriate answer for each of the following questions.               1. What does the “true gratitude” mean?                    A. A way of life.                      B. A joyous occasion.                  C. A much deeper level of gratitude.                                  D. The improvement of the quality of life.                 2. Who has so many things to be grateful for?                  A. A successful man.                  B. A miserable person.                  C. A good-tempered man.                          D.All of us.                       3.        In the sentence “Expressing love and gratitude  satisfies our deep sense of purpose”, the purpose includes all of the following  EXCEPT ________.                                      A. spiritual health.                                      B. emotional health.                                    C. physical health.                                                     D. social health.                     4. What kind of gift is suitable  for mother on Mother’s Day according to the author?                          A. Carnation.                                    B. Lily.                                    C. Accessories.                                                     D. Greeting cards.               5. If a friend does you a favor, you can do all of the following EXCEPT ________.                        A. treat him in a restaurant.                        B. buy ice-cream for him.                C. just say “thank you”.                        D. ask him to help next time.    

以上結果有多餘的空格、分行符號,輸出文本看起來很散亂,但至少內容是擷取正確了。再在task2-5的html檔案驗證一下,也擷取到了正確的內容,證明方法可行。接下來我們可以集中精力解決格式散亂的問題。

1.2 美化文本輸出

最主要的問題是有多餘的空格、分行符號。想到的一個辦法是:將所有結點的內容(包括文本結果)trim,即去年前後的所有空白字元,並對於br元素,加入一個分行符號。也即類比了一下html文檔的render效果(因為在瀏覽器中顯示是正確的,所以採用同樣的方法,也能得到相同的結果)。 要實現這個方法,要擷取一個元素的所有的子結果,使用cheerio的contents函數,這個函數擷取一個元素的所有子項目(包括文本元素)。然後調用字串的trim函數去除首尾的空白文本。由於子項目又有子項目,因此使用遞迴函式。代碼如下:

function getContent(node){    var a = node.contents();    if (a.length == 0) {        if (node.is(‘br‘)){            RST+=‘\n‘;        } else {            RST+=node.text().trim();;        }    } else {        node.contents().each(function(i, elem){            getContent($(this));        });        if (node.is(‘p‘) || node.is(‘tr‘)){            RST+=‘\n‘;        }    }}

 

getContent函數用於擷取一個元素的常值內容,輸入參數為元素,這個函數會被遞迴調用。首先調用contents函數擷取所有子項目。如果子項目數目為0,表示這個元素是葉結點,則首先判斷如果是br元素,則在結果中加入一個分行符號,否則,調用text函數擷取這個元素的常值內容。 如果子項目大於0,則遞迴地處理所有子項目。如果當前元素為p或tr元素,則在結果中加入一個換行。 其中RST為一個全域變數,用於儲存結果文本。在調用函數前需要設定為空白字串。 這樣處理後,結果如下:

Task  1: You will be given 10 minutes to read the text for the first time and thenchoose  an appropriate answer for each of the following questions.1. What does the “true gratitude” mean?A.A way of life.B.A joyous occasion.C.A much deeper level of gratitude.D.The improvement of the quality of life.2. Who has so many things to be grateful for?A.A successful man.B.A miserable person.C.A good-tempered man.D.All of us.3.In the sentence “Expressing love and gratitude  satisfies our deep sense of purpose”, the purpose includes all of the following  EXCEPT ________.A.spiritual health.B.emotional health.C.physical health.D.social health.4. What kind of gift is suitable  for mother on Mother’s Day according to the author?A.Carnation.B.Lily.C.Accessories.D.Greeting cards.5. If a friend does you a favor, you can do all of the following EXCEPT ________.A.treat him in a restaurant.B.buy ice-cream for him.C.just say “thank you”.D.ask him to help next time.

看起來漂亮多了。 問題文本提取成功,接下來再提取答案文本。

1.3 提取答案文本

在html源檔案中搜尋answer,可以看出,答案是儲存在script中的,如下:

<SCRIPT LANGUAGE="JavaScript">  var StandardAnswer = new Array()   StandardAnswer =["C","D","D","D","D"]</SCRIPT>

 

選擇題的答案儲存在StandardAnswer的數組中。則擷取答案文本的方法為:先擷取script元素中的代碼文本,再通過eval函數得到這個數組值,最後產生答案文本。代碼如下:

var t = $(‘html‘).find(‘script‘);var A = undefined;t.each(function(i, elem) {    var text = $(this).text();    if (text.match(‘StandardAnswer‘)){        var a = eval(text);        console.log("standardanswer: "+ a);        A= a;    }});

 

變數A儲存答案數組。通過判斷文本中是否包含‘StandardAnswer‘來判斷是否是目標代碼。然後將這個代碼傳給eval,傳回值即為‘["C","D","D","D","D"]‘這個數組。 有了答案數組,產生答案文本就比較容易了。

1.4 最終代碼

可以在這查看最終代碼。 最終的代碼還解決了一些小問題,如問題文本中包含了多餘的文本(對於task4),task4的答案也會被顯示在問題文本中,沒有留下空白填寫答案等。 整個分析、編碼過程大致3個小時。其中檔案a.js用於產生問題文本,b.js用於產生答案文本。a.js與b.js有很大的重複(b.js是直接複製了一份a.js修改而來)。這個代碼基本上是解決一次性問題,沒有什麼重用性(在編寫的過程中也沒有考慮這些)。但是最重要的是:它解決了問題,它能夠工作。它不需要那麼好!最後,這個程式被用於處理幾十個檔案,成功正確地產生了問題文本及答案文本。

Author: Astropeak

Created: 2016-12-18 Sun 16:36

Emacs 25.1.1 (Org mode 8.2.10)

Validate

nodejs cheerio模組提取html頁面內容

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.