網路爬蟲——爬百度貼吧

life4711發表於2015-12-28

功能:輸入話題的編號(一般在百度貼吧裡面找)然後爬取樓主的所有發言的文字部分。

說明:中文編碼和儲存檔案較上一篇又有新的方式,特此留存。

#coding: utf-8  
import string
import urllib2
import re

class HTML_Tool:#作用就是將html檔案裡的一些標籤去掉,只保留文字部分
	BgnCharToNoneRex = re.compile("(\t|\n| |<a.*?>|<img.*?>)")
	EndCharToNoneRex = re.compile("<.*?>")
	BgnPartRex = re.compile("<p.*?>")
	CharToNewLineRex = re.compile("<br/>|</p>|<tr>|<div>|</div>")
	CharToNextTabRex = re.compile("<td>")
	
	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)
		return x
		
class Baidu_Spider:
	def __init__(self,url):
		self.myUrl=url+'?see_lz=1'
		self.datas = []
		self.myTool = HTML_Tool()
		print u'已經啟動百度貼吧爬蟲'
	def baidu_tieba(self):
		#在做編碼轉換時,通常需要以unicode作為中間編碼
		#即先將其他編碼的字串解碼(decode)成unicode,再從unicode編碼(encode)成另一種編碼
		myPage = urllib2.urlopen(self.myUrl).read().decode("utf-8")#decode的作用是將其他編碼的字串轉換成unicode編碼
		endPage = self.page_counter(myPage)
		title = self.find_title(myPage)
		print u'文章名稱: '+title
		self.save_data(self.myUrl,title,endPage)
	
	def page_counter(self,myPage):
		myMatch = re.search(r'class="red">(\d+?)</span>',myPage,re.S)
		if myMatch:
			endPage = int(myMatch.group(1))
			print u'爬蟲報告:發現樓主共有%d頁的原創內容' % endPage
		else:
			endPage = 0
			print u'爬蟲報告: 無法計算樓主釋出的內容有多少頁!'
		return endPage
	def find_title(self,myPage):
		myMatch = re.search(r'<h1.*?>(.*?)</h1>',myPage,re.S)
		title = u'暫無標題'
		if myMatch:
			title = myMatch.group(1)
		else: 
			print u'爬蟲報告:無法載入文章標題!'
		title = title.replace('\\','').replace('/','').replace(':','').replace('?','').replace('>','').replace('<','').replace("|",'')
		return title
	def save_data(self,url,title,endPage):
		self.get_data(url,endPage)
		f = open(title+'.txt','w+')
		f.writelines(self.datas)
		f.close()
		print u'爬蟲報告:檔案以及下載到本地並打包成txt檔案'
		print u'載入完成,按任意鍵退出...'
		raw_input();
		
	def get_data(self,url,endPage):
		url = url + '&pn='
		for i in range(1,endPage+1):
			print u'爬蟲報告:爬蟲%d號正在載入中...' % i
			myPage = urllib2.urlopen(url + str(i)).read()
			self.deal_data(myPage.decode('utf-8'))
	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('utf-8'))
			self.datas.append(data+'\n')
			#self.datas.append(item.replace("\n","").encode('utf-8')+'\n')
print u'請輸入貼吧地址最後的字串: '
bdurl = 'http://tieba.baidu.com/p/' + str(raw_input(u'htttp://tieba.baidu.com/p/'))

mySpider = Baidu_Spider(bdurl)
mySpider.baidu_tieba()

後記:學了一週多的爬蟲,把《python學習手冊》大體翻了一遍,感覺對Python語言的基礎瞭解一些了。至於爬蟲程式,參照大神的部落格,依樣畫葫蘆也算是實現了兩個小爬蟲。時間不允許了,我也不準備深究了,以後用到再擴充吧!


相關文章