在Python中使用HTMLParser解析HTML的教程

來源:互聯網
上載者:User
如果我們要編寫一個搜尋引擎,第一步是用爬蟲把目標網站的頁面抓下來,第二步就是解析該HTML頁面,看看裡面的內容到底是新聞、圖片還是視頻。

假設第一步已經完成了,第二步應該如何解析HTML呢?

HTML本質上是XML的子集,但是HTML的文法沒有XML那麼嚴格,所以不能用標準的DOM或SAX來解析HTML。

好在Python提供了HTMLParser來非常方便地解析HTML,只需簡單幾行代碼:

from HTMLParser import HTMLParserfrom htmlentitydefs import name2codepointclass MyHTMLParser(HTMLParser):  def handle_starttag(self, tag, attrs):    print('<%s>' % tag)  def handle_endtag(self, tag):    print('' % tag)  def handle_startendtag(self, tag, attrs):    print('<%s/>' % tag)  def handle_data(self, data):    print('data')  def handle_comment(self, data):    print('')  def handle_entityref(self, name):    print('&%s;' % name)  def handle_charref(self, name):    print('&#%s;' % name)parser = MyHTMLParser()parser.feed('

Some html tutorial...
END

')

feed()方法可以多次調用,也就是不一定一次把整個HTML字串都塞進去,可以一部分一部分塞進去。

特殊字元有兩種,一種是英文表示的 ,一種是數字表示的Ӓ,這兩種字元都可以通過Parser解析出來。
小結

找一個網頁,例如https://www.python.org/events/python-events/,用瀏覽器查看源碼並複製,然後嘗試解析一下HTML,輸出Python官網發布的會議時間、名稱和地點。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.