本文實(shí)例講述了基于Python實(shí)現(xiàn)的百度貼吧網(wǎng)絡(luò)爬蟲。分享給大家供大家參考。具體如下:
完整實(shí)例代碼點(diǎn)擊此處本站下載。
項(xiàng)目內(nèi)容:
用Python寫的百度貼吧的網(wǎng)絡(luò)爬蟲。
使用方法:
新建一個(gè)BugBaidu.py文件,然后將代碼復(fù)制到里面后,雙擊運(yùn)行。
程序功能:
將貼吧中樓主發(fā)布的內(nèi)容打包txt存儲到本地。
原理解釋:
首先,先瀏覽一下某一條貼吧,點(diǎn)擊只看樓主并點(diǎn)擊第二頁之后url發(fā)生了一點(diǎn)變化,變成了:
http://tieba.baidu.com/p/2296712428?see_lz=1&pn=1
可以看出來,see_lz=1是只看樓主,pn=1是對應(yīng)的頁碼,記住這一點(diǎn)為以后的編寫做準(zhǔn)備。
這就是我們需要利用的url。
接下來就是查看頁面源碼。
首先把題目摳出來存儲文件的時(shí)候會用到。
可以看到百度使用gbk編碼,標(biāo)題使用h1標(biāo)記:
同樣,正文部分用div和class綜合標(biāo)記,接下來要做的只是用正則表達(dá)式來匹配即可。
運(yùn)行截圖:

生成的txt文件:

# -*- coding: utf-8 -*- #--------------------------------------- # 程序:百度貼吧爬蟲 # 版本:0.5 # 作者:why # 日期:2013-05-16 # 語言:Python 2.7 # 操作:輸入網(wǎng)址后自動只看樓主并保存到本地文件 # 功能:將樓主發(fā)布的內(nèi)容打包txt存儲到本地。 #--------------------------------------- import string import urllib2 import re #----------- 處理頁面上的各種標(biāo)簽 ----------- class HTML_Tool: # 用非 貪婪模式 匹配 /t 或者 /n 或者 空格 或者 超鏈接 或者 圖片 BgnCharToNoneRex = re.compile("(/t|/n| |<a.*?>|<img.*?>)") # 用非 貪婪模式 匹配 任意<>標(biāo)簽 EndCharToNoneRex = re.compile("<.*?>") # 用非 貪婪模式 匹配 任意<p>標(biāo)簽 BgnPartRex = re.compile("<p.*?>") CharToNewLineRex = re.compile("(<br/>|</p>|<tr>|<div>|</div>)") CharToNextTabRex = re.compile("<td>") # 將一些html的符號實(shí)體轉(zhuǎn)變?yōu)樵挤? replaceTab = [("<","<"),(">",">"),("&","&"),("&","/""),(" "," ")] def Replace_Char(self,x): x = self.BgnCharToNoneRex.sub("",x) x = self.BgnPartRex.sub("/n ",x) x = self.CharToNewLineRex.sub("/n",x) x = self.CharToNextTabRex.sub("/t",x) x = self.EndCharToNoneRex.sub("",x) for t in self.replaceTab: x = x.replace(t[0],t[1]) return x class Baidu_Spider: # 申明相關(guān)的屬性 def __init__(self,url): self.myUrl = url + '?see_lz=1' self.datas = [] self.myTool = HTML_Tool() print u'已經(jīng)啟動百度貼吧爬蟲,咔嚓咔嚓' # 初始化加載頁面并將其轉(zhuǎn)碼儲存 def baidu_tieba(self): # 讀取頁面的原始信息并將其從gbk轉(zhuǎn)碼 myPage = urllib2.urlopen(self.myUrl).read().decode("gbk") # 計(jì)算樓主發(fā)布內(nèi)容一共有多少頁 endPage = self.page_counter(myPage) # 獲取該帖的標(biāo)題 title = self.find_title(myPage) print u'文章名稱:' + title # 獲取最終的數(shù)據(jù) self.save_data(self.myUrl,title,endPage) #用來計(jì)算一共有多少頁 def page_counter(self,myPage): # 匹配 "共有<span class="red">12</span>頁" 來獲取一共有多少頁 myMatch = re.search(r'class="red">(/d+?)</span>', myPage, re.S) if myMatch: endPage = int(myMatch.group(1)) print u'爬蟲報(bào)告:發(fā)現(xiàn)樓主共有%d頁的原創(chuàng)內(nèi)容' % endPage else: endPage = 0 print u'爬蟲報(bào)告:無法計(jì)算樓主發(fā)布內(nèi)容有多少頁!' return endPage # 用來尋找該帖的標(biāo)題 def find_title(self,myPage): # 匹配 <h1 class="core_title_txt" title="">xxxxxxxxxx</h1> 找出標(biāo)題 myMatch = re.search(r'<h1.*?>(.*?)</h1>', myPage, re.S) title = u'暫無標(biāo)題' if myMatch: title = myMatch.group(1) else: print u'爬蟲報(bào)告:無法加載文章標(biāo)題!' # 文件名不能包含以下字符: / / : * ? " < > | title = title.replace('//','').replace('/','').replace(':','').replace('*','').replace('?','').replace('"','').replace('>','').replace('<','').replace('|','') return title # 用來存儲樓主發(fā)布的內(nèi)容 def save_data(self,url,title,endPage): # 加載頁面數(shù)據(jù)到數(shù)組中 self.get_data(url,endPage) # 打開本地文件 f = open(title+'.txt','w+') f.writelines(self.datas) f.close() print u'爬蟲報(bào)告:文件已下載到本地并打包成txt文件' print u'請按任意鍵退出...' raw_input(); # 獲取頁面源碼并將其存儲到數(shù)組中 def get_data(self,url,endPage): url = url + '&pn=' for i in range(1,endPage+1): print u'爬蟲報(bào)告:爬蟲%d號正在加載中...' % i myPage = urllib2.urlopen(url + str(i)).read() # 將myPage中的html代碼處理并存儲到datas里面 self.deal_data(myPage.decode('gbk')) # 將內(nèi)容從頁面代碼中摳出來 def deal_data(self,myPage): myItems = re.findall('id="post_content.*?>(.*?)</div>',myPage,re.S) for item in myItems: data = self.myTool.Replace_Char(item.replace("/n","").encode('gbk')) self.datas.append(data+'/n') #-------- 程序入口處 ------------------ print u"""#--------------------------------------- # 程序:百度貼吧爬蟲 # 版本:0.5 # 作者:why # 日期:2013-05-16 # 語言:Python 2.7 # 操作:輸入網(wǎng)址后自動只看樓主并保存到本地文件 # 功能:將樓主發(fā)布的內(nèi)容打包txt存儲到本地。 #--------------------------------------- """ # 以某小說貼吧為例子 # bdurl = 'http://tieba.baidu.com/p/2296712428?see_lz=1&pn=1' print u'請輸入貼吧的地址最后的數(shù)字串:' bdurl = 'http://tieba.baidu.com/p/' + str(raw_input(u'http://tieba.baidu.com/p/')) #調(diào)用 mySpider = Baidu_Spider(bdurl) mySpider.baidu_tieba()希望本文所述對大家的Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選