Python之HTML的解析(網頁抓取一)

來源:互聯網
上載者:User

標籤:

http://blog.csdn.net/my2010sam/article/details/14526223

---------------------

對html的解析是網頁抓取的基礎,分析抓取的結果找到自己想要的內容或標籤以達到抓取的目的。   

    HTMLParser是python用來解析html的模組。它可以分析出html裡面的標籤、資料等等,是一種處理html的簡便途徑。 HTMLParser採用的是一種事件驅動的模式,當HTMLParser找到一個特定的標記時,它會去調用一個使用者定義的函數,以此來通知程式處理它主要的使用者回呼函數的命名都是以handler_開頭的,都是HTMLParser的成員函數。當我們使用時,就從HTMLParser派生出新的類,然後重新定義這幾個以handler_開頭的函數即可。這幾個函數包括:

  • handle_startendtag  處理開始標籤和結束標籤
  • handle_starttag     處理開始標籤,比如<xx>   tag不區分大小寫
  • handle_endtag       處理結束標籤,比如</xx>
  • handle_charref      處理特殊字元串,就是以&#開頭的,一般是內碼錶示的字元
  • handle_entityref    處理一些特殊字元,以&開頭的,比如 &nbsp;
  • handle_data         處理資料,就是<xx>data</xx>中間的那些資料
  • handle_comment      處理注釋
  • handle_decl         處理<!開頭的,比如<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
  • handle_pi           處理形如<?instruction>的東西

def handle_starttag(self,tag,attr):
        #注意:tag不區分大小寫,此時也可以解析 <A 標籤

        # SGMLParser 會在建立attrs 時將屬性名稱轉化為小寫。

        if tag==‘a‘:
            for href,link in attr:
                if href.lower()=="href":

                        pass

 

1. 基本解析,找到開始和結束標籤

 

[python] view plaincopy 
  1. <span style="font-size:18px;">#coding:utf-8  
  2.   
  3. from HTMLParser import HTMLParser  
  4. ‘‘‘‘‘ 
  5. HTMLParser的成員函數: 
  6.  
  7.     handle_startendtag  處理開始標籤和結束標籤 
  8.     handle_starttag     處理開始標籤,比如<xx> 
  9.     handle_endtag       處理結束標籤,比如</xx> 
  10.     handle_charref      處理特殊字元串,就是以&#開頭的,一般是內碼錶示的字元 
  11.     handle_entityref    處理一些特殊字元,以&開頭的,比如   
  12.     handle_data         處理資料,就是<xx>data</xx>中間的那些資料 
  13.     handle_comment      處理注釋 
  14.     handle_decl         處理<!開頭的,比如<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” 
  15.     handle_pi           處理形如<?instruction>的東西 
  16.  
  17. ‘‘‘  
  18. class myHtmlParser(HTMLParser):  
  19.     #處理<!開頭的內容  
  20.     def handle_decl(self,decl):  
  21.         print ‘Encounter some declaration:‘+ decl  
  22.     def handle_starttag(self,tag,attrs):  
  23.         print ‘Encounter the beginning of a %s tag‘ % tag  
  24.     def handle_endtag(self,tag):  
  25.         print ‘Encounter the end of a %s tag‘ % tag  
  26.     #處理注釋  
  27.     def handle_comment(self,comment):   
  28.         print ‘Encounter some comments:‘ + comment  
  29.   
  30.   
  31. if __name__==‘__main__‘:  
  32.     a = ‘<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\  
  33.     <html><head><!--insert javaScript here!--><title>test</title><body><a href="http: //www.163.com">連結到163</a></body></html>‘  
  34.     m=myHtmlParser()  
  35.     m.feed(a)  
  36.     m.close()  
  37.   
  38. 輸出結果:  
  39.   
  40. Encounter some declaration:DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"  
  41. Encounter the beginning of a html tag  
  42. Encounter the beginning of a head tag  
  43. Encounter some comments:insert javaScript here!  
  44. Encounter the beginning of a title tag  
  45. Encounter the end of a title tag  
  46. Encounter the beginning of a body tag  
  47. Encounter the beginning of a a tag  
  48. Encounter the end of a a tag  
  49. Encounter the end of a body tag  
  50. Encounter the end of a html tag</span>  

 

 

2. 解析html的超連結和連結顯示的內容  

 

[python] view plaincopy 
  1. <span style="font-size:18px;">#coding:utf-8  
  2. from HTMLParser import HTMLParser  
  3. class myHtmlParser(HTMLParser):  
  4.   
  5.     def __init__(self):  
  6.         HTMLParser.__init__(self)  
  7.         self.flag=None  
  8.   
  9.     # 這裡重新定義了處理開始標籤的函數  
  10.     def handle_starttag(self,tag,attrs):  
  11.          # 判斷標籤<a>的屬性  
  12.         if tag==‘a‘:  
  13.             self.flag=‘a‘  
  14.             for href,link in attrs:  
  15.                 if href==‘href‘:  
  16.                     print "href:",link  
  17.   
  18.     def handle_data(self,data):  
  19.         if self.flag==‘a‘:  
  20.             print "data:",data.decode(‘utf-8‘)  
  21.   
  22. if __name__ == ‘__main__‘:  
  23.     a = ‘<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\  
  24.     <html><head><!--insert javaScript here!--><title>test</title><body><a href="http: //www.163.com">連結到163</a></body></html>‘  
  25.     m=myHtmlParser()  
  26.     m.feed(a)  
  27.     m.close()  
  28.   
  29. 輸出結果:  
  30.   
  31. href: http: //www.163.com  
  32. data: 連結到163</span>  

 

 

或:

 

[python] view plaincopy 
    1. <span style="font-size:18px;">#coding:utf-8  
    2.   
    3. from  HTMLParser import HTMLParser  
    4. import urllib2  
    5.   
    6. class myparser(HTMLParser):  
    7.   
    8.     # 繼承父類初始化方法,並添加一個tag屬性  
    9.     def __init__(self):  
    10.         HTMLParser.__init__(self)  
    11.         self.tag = None  
    12.   
    13.     def handle_decl(self,decl):  
    14.         print u"聲明:",decl  
    15.   
    16.     def handle_starttag(self,tag,attrs):  
    17.         print u"開始標籤;",tag  
    18.   
    19.         # 判斷是否是a開頭的標籤  
    20.         if tag==‘a‘ and len(attrs):  
    21.             #設定 self.tag 標記  
    22.             self.tag=‘a‘  
    23.             for href,link in attrs:  
    24.                 if href==‘href‘:  
    25.                     print href+":"+link  
    26.   
    27.     def handle_endtag(self,tag):  
    28.         print u"結束標籤:",tag  
    29.   
    30.     def handle_data(self,data):  
    31.         #處理 a 標籤開頭的資料  
    32.         if self.tag==‘a‘:  
    33.             print u"資料內容:",data.decode("utf-8")  
    34.   
    35.     def handle_comment(self,comm):  
    36.         print u"注釋:",comm  
    37.   
    38.   
    39. if __name__ == ‘__main__‘:  
    40.   
    41.     a = ‘<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\  
    42.     <html><head><!--insert javaScript here!--><title>test</title><body><a href="http: //www.163.com">連結到163</a><a href="http: //www.baidu.com">百度</a></body></html>‘  
    43.     m = myparser()  
    44.     m.feed(a)  
    45.   
    46.   
    47.   
    48.   
    49.   
    50. 結果:  
    51.   
    52. 聲明: DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"  
    53. 開始標籤; html  
    54. 開始標籤; head  
    55. 注釋: insert javaScript here!  
    56. 開始標籤; title  
    57. 結束標籤: title  
    58. 開始標籤; body  
    59. 開始標籤; a  
    60. href:http: //www.163.com  
    61. 資料內容: 連結到163  
    62. 結束標籤: a  
    63. 開始標籤; a  
    64. href:http: //www.baidu.com  
    65. 資料內容: 百度  
    66. 結束標籤: a  
    67. 結束標籤: body  
    68. 結束標籤: html</span>  

Python之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.