在抓取網頁信息時,常常要對網頁中特定位置信息進行查找,好比查找標題所在的位置,正文內容所在位置,須要用到相似於操做系統下*和?這樣的通配符,在python中把相似的一些符號組成的表達式稱爲正則表達式,要在程序中使用正則表達式需先使用import re進行說明,加載re模塊。html
經常使用的正則表達式符號有:python
符號 | 含義 | 舉例 | 完整匹配的字符串 |
. | 匹配除\n外的任意一個字符 | a.c | abc |
\t | 匹配tab符號 | ||
\n | 匹配換行符 | ||
\d | 匹配任意一個數字 | a\dc | a1c |
傳送門:1.Python正則表達式指南 2.Python中的正則表達式(re)正則表達式
下面這個例子能夠在百度帖吧的指定帖子中爬取樓主發佈的全部內容:數組
1 #coding:utf-8 2 ''' 3 Created on 2016年12月16日 4 5 @author: liukain 6 ''' 7 # -*- coding: utf-8 -*- 8 #--------------------------------------- 9 # 程序:百度貼吧爬蟲 10 11 # 語言:Python 2.7 12 # 操做:輸入網址後自動只看樓主並保存到本地文件 13 # 功能:將樓主發佈的內容打包txt存儲到本地。 14 #--------------------------------------- 15 16 import string 17 import urllib2 18 import re 19 #----------- 處理頁面上的各類標籤 ----------- 20 class HTML_Tool: 21 # 用非 貪婪模式 匹配 \t 或者 \n 或者 空格 或者 超連接 或者 圖片 22 BgnCharToNoneRex = re.compile("(\t|\n| |<a.*?>|<img.*?>)") 23 # 用非 貪婪模式 匹配 任意<>標籤 24 EndCharToNoneRex = re.compile("<.*?>") 25 # 用非 貪婪模式 匹配 任意<p>標籤 26 BgnPartRex = re.compile("<p.*?>") 27 CharToNewLineRex = re.compile("(<br/>|</p>|<tr>|<div>|</div>)") 28 CharToNextTabRex = re.compile("<td>") 29 # 將一些html的符號實體轉變爲原始符號 30 replaceTab = [("<","<"),(">",">"),("&","&"),("&","\""),(" "," ")] 31 32 def Replace_Char(self,x): 33 x = self.BgnCharToNoneRex.sub("",x) 34 x = self.BgnPartRex.sub("\n ",x) 35 x = self.CharToNewLineRex.sub("\n",x) 36 x = self.CharToNextTabRex.sub("\t",x) 37 x = self.EndCharToNoneRex.sub("",x) 38 39 for t in self.replaceTab: 40 x = x.replace(t[0],t[1]) 41 return x 42 43 class Baidu_Spider: 44 # 申明相關的屬性 45 def __init__(self,url): 46 self.myUrl = url + '?see_lz=1' 47 self.datas = [] 48 self.myTool = HTML_Tool() 49 print u'已經啓動百度貼吧爬蟲,咔嚓咔嚓' 50 51 # 初始化加載頁面並將其轉碼儲存 52 def baidu_tieba(self): 53 # 讀取頁面的原始信息並將其從gbk轉碼 54 myPage = urllib2.urlopen(self.myUrl).read().decode("utf_8") 55 # 計算樓主發佈內容一共有多少頁 56 endPage = self.page_counter(myPage) 57 # 獲取該帖的標題 58 title = self.find_title(myPage) 59 print u'文章名稱:' + title 60 # 獲取最終的數據 61 self.save_data(self.myUrl,title,endPage) 62 63 #用來計算一共有多少頁 64 def page_counter(self,myPage): 65 # 匹配 "共有<span class="red">12</span>頁" 來獲取一共有多少頁 66 myMatch = re.search(r'class="red">(\d+?)</span>', myPage, re.S) 67 if myMatch: 68 endPage = int(myMatch.group(1)) 69 print u'爬蟲報告:發現樓主共有%d頁的原創內容' % endPage 70 else: 71 endPage = 0 72 print u'爬蟲報告:沒法計算樓主發佈內容有多少頁!' 73 return endPage 74 75 # 用來尋找該帖的標題 76 def find_title(self,myPage): 77 # 匹配 <h1 class="core_title_txt" title="">xxxxxxxxxx</h1> 找出標題 78 myMatch = re.search(r'<h1.*?>(.*?)</h1>', myPage, re.S) 79 title = u'暫無標題' 80 if myMatch: 81 title = myMatch.group(1) 82 else: 83 print u'爬蟲報告:沒法加載文章標題!' 84 # 文件名不能包含如下字符: \ / : * ? " < > | 85 title = title.replace('\\','').replace('/','').replace(':','').replace('*','').replace('?','').replace('"','').replace('>','').replace('<','').replace('|','') 86 return title 87 88 89 # 用來存儲樓主發佈的內容 90 def save_data(self,url,title,endPage): 91 # 加載頁面數據到數組中 92 self.get_data(url,endPage) 93 # 打開本地文件 94 f = open(title+'.txt','w+') 95 f.writelines(self.datas) 96 f.close() 97 print u'爬蟲報告:文件已下載到本地並打包成txt文件' 98 print u'請按任意鍵退出...' 99 raw_input(); 100 101 # 獲取頁面源碼並將其存儲到數組中 102 def get_data(self,url,endPage): 103 url = url + '&pn=' 104 for i in range(1,endPage+1): 105 print u'爬蟲報告:爬蟲%d號正在加載中...' % i 106 myPage = urllib2.urlopen(url + str(i)).read() 107 # 將myPage中的html代碼處理並存儲到datas裏面 108 self.deal_data(myPage.decode('utf-8')) 109 110 # 將內容從頁面代碼中摳出來 111 def deal_data(self,myPage): 112 myItems = re.findall('id="post_content.*?>(.*?)</div>',myPage,re.S) 113 for item in myItems: 114 data = self.myTool.Replace_Char(item.replace("\n","").encode('utf-8')) 115 self.datas.append(data+'\n') 116 117 #-------- 程序入口處 ------------------ 118 print u"""#--------------------------------------- 119 # 程序:百度貼吧爬蟲 120 121 # 語言:Python 2.7 122 # 操做:輸入網址後自動只看樓主並保存到本地文件 123 # 功能:將樓主發佈的內容打包txt存儲到本地。 124 #--------------------------------------- 125 """ 126 127 # 以某小說貼吧爲例子 128 # bdurl = 'http://tieba.baidu.com/p/2296712428?see_lz=1&pn=1' 129 print u'請輸入貼吧的地址最後的數字串:' 130 bdurl = 'http://tieba.baidu.com/p/' + str(raw_input(u'http://tieba.baidu.com/p/')) 131 #調用 132 mySpider = Baidu_Spider(bdurl) 133 mySpider.baidu_tieba()
第22行:re.compile將經常使用的正則表達式規則存儲爲一個對象,方便後面使用。app
問題:第22行,超連接爲何是a打頭?第30行replaceTab的用法沒看懂。ide
第33行,對象.sub用法:sub是substitute的所寫,表示替換,用來實現經過正則表達式,實現比普通字符串的replace更增強大的替換功能。post
關於sub用法的傳送門:詳解Python中的re.subui
運行效果以下:編碼
下面這個例子應該能夠從糗事百科中提取裏面的內容,可是我沒有運行成功,老是卡在「正在加載中請稍候....」那,就沒反應了,之後有時間再研究一下:url
1 # -*- coding: utf-8 -*- 2 ''' 3 Created on 2016年12月16日 4 5 @author: liukain 6 ''' 7 #--------------------------------------- 8 # 程序:糗百爬蟲 9 # 語言:Python 2.7 10 # 操做:輸入quit退出閱讀糗事百科 11 # 功能:按下回車依次瀏覽今日的糗百熱點 12 # 更新:解決了命令提示行下亂碼的問題 13 #--------------------------------------- 14 import urllib2 15 import urllib 16 import re 17 import thread 18 import time 19 20 #----------- 處理頁面上的各類標籤 ----------- 21 class HTML_Tool: 22 # 用非 貪婪模式 匹配 \t 或者 \n 或者 空格 或者 超連接 或者 圖片 23 BgnCharToNoneRex = re.compile("(\t|\n| |<a.*?>|<img.*?>)") 24 # 用非 貪婪模式 匹配 任意<>標籤 25 EndCharToNoneRex = re.compile("<.*?>") 26 # 用非 貪婪模式 匹配 任意<p>標籤 27 BgnPartRex = re.compile("<p.*?>") 28 CharToNewLineRex = re.compile("(<br/>|</p>|<tr>|<div>|</div>)") 29 CharToNextTabRex = re.compile("<td>") 30 # 將一些html的符號實體轉變爲原始符號 31 replaceTab = [("<","<"),(">",">"),("&","&"),("&","\""),(" "," ")] 32 def Replace_Char(self,x): 33 x = self.BgnCharToNoneRex.sub("",x) 34 x = self.BgnPartRex.sub("\n ",x) 35 x = self.CharToNewLineRex.sub("\n",x) 36 x = self.CharToNextTabRex.sub("\t",x) 37 x = self.EndCharToNoneRex.sub("",x) 38 for t in self.replaceTab: 39 x = x.replace(t[0],t[1]) 40 return x 41 #----------- 處理頁面上的各類標籤 ----------- 42 #----------- 加載處理糗事百科 ----------- 43 class HTML_Model: 44 def __init__(self): 45 self.page = 1 46 self.pages = [] 47 self.myTool = HTML_Tool() 48 self.enable = False 49 50 # http://m.qiushibaike.com/hot/將全部的段子都扣出來,添加到列表中而且返回列表 http://www.qiushibaike.com/hot/ 51 def GetPage(self,page): 52 myUrl = "http://m.qiushibaike.com/hot/" + page 53 myResponse = urllib2.urlopen(myUrl) 54 myPage = myResponse.read() 55 #encode的做用是將unicode編碼轉換成其餘編碼的字符串 56 #decode的做用是將其餘編碼的字符串轉換成unicode編碼 57 unicodePage = myPage.decode("utf-8") 58 # 找出全部class="content"的div標記 59 #re.S是任意匹配模式,也就是.能夠匹配換行符 60 myItems = re.findall('<div.*?class="content".*?title="(.*?)">(.*?)</div>',unicodePage,re.S) 61 items = [] 62 for item in myItems: 63 # item 中第一個是div的標題,也就是時間 64 # item 中第二個是div的內容,也就是內容 65 items.append([item[0].replace("\n",""),item[1].replace("\n","")]) 66 return items 67 # 用於加載新的段子 68 def LoadPage(self): 69 # 若是用戶未輸入quit則一直運行 70 while self.enable: 71 # 若是pages數組中的內容小於2個 72 if len(self.pages) > 2: 73 try: 74 # 獲取新的頁面中的段子們 75 myPage = self.GetPage(str(self.page)) 76 self.page += 1 77 self.pages.append(myPage) 78 except: 79 print '沒法連接糗事百科!' 80 else: 81 time.sleep(1) 82 83 def ShowPage(self,q,page): 84 for items in q: 85 print u'第%d頁' % page , items[0] 86 print self.myTool.Replace_Char(items[1]) 87 myInput = raw_input() 88 if myInput == "quit": 89 self.enable = False 90 break 91 def Start(self): 92 self.enable = True 93 page = self.page 94 95 print u'正在加載中請稍候......' 96 97 # 新建一個線程在後臺加載段子並存儲 98 thread.start_new_thread(self.LoadPage,()) 99 100 #----------- 加載處理糗事百科 ----------- 101 while self.enable: 102 # 若是self的page數組中存有元素 103 if self.pages: 104 nowPage = self.pages[0] 105 del self.pages[0] 106 self.ShowPage(nowPage,page) 107 page += 1 108 109 #----------- 程序的入口處 ----------- 110 print u""" 111 --------------------------------------- 112 程序:糗百爬蟲 113 版本:0.1 114 115 語言:Python 2.7 116 操做:輸入quit退出閱讀糗事百科 117 功能:按下回車依次瀏覽今日的糗百熱點 118 --------------------------------------- 119 """ 120 121 122 print u'請按下回車瀏覽今日的糗百內容:' 123 raw_input(' ') 124 myModel = HTML_Model() 125 myModel.Start()
個人運行效果: