网络爬虫——爬百度贴吧

功能:输入话题的编号(一般在百度贴吧里面找)然后爬取楼主的所有发言的文字部分。

说明:中文编码和保存文件较上一篇又有新的方式,特此留存。

#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语言的基础了解一些了。至于爬虫程序,参照大神的博客,依样画葫芦也算是实现了两个小爬虫。时间不允许了,我也不准备深究了,以后用到再拓展吧!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值