您的位置:首页 > 编程语言 > Python开发

Python爬虫入门学习例子之百度贴吧

2016-10-03 22:41 393 查看
初学Python爬虫,学习资料是这篇博客:Python爬虫入门教程 接着上一篇文章糗事百科爬虫再列出一个爬百度贴吧的例子。

# 程序:百度贴吧爬虫
# 语言:Python 2.7
# 操作:输入网址后自动只看楼主并保存到本地文件
# 功能:将楼主发布的小说内容打包txt存储到本地。
#---------------------------------------

import urllib2
import re

#----------- 处理html页面上的各种标签 -----------
#这个类应该是写好的,直接用就行,作用就是把与我们的小说内容无关的东西去掉
class HTML_Tool:
# 用非 贪婪模式 匹配 \t 或者 \n 或者 空格 或者 超链接 或者 图片
BgnCharToNoneRex = re.compile("(\t|\n| |<a.*?>|<img.*?>)")

# 用非 贪婪模式 匹配 任意<>标签
EndCharToNoneRex = re.compile("<.*?>")

# 用非 贪婪模式 匹配 任意<p>标签
BgnPartRex = re.compile("<p.*?>")
CharToNewLineRex = re.compile("(<br/>|</p>|<tr>|<div>|</div>)")
CharToNextTabRex = re.compile("<td>")

# 将一些html的符号实体转变为原始符号
replaceTab = [("<","<"),(">",">"),("&","&"),("&","\""),(" "," ")]

def Replace_Char(self,x):
#sub是替换,前边的替换后边的
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:
#初始化属性
def __init__(self,url):
#'?see_lz=1'表示只看楼主(找个贴吧看一下就懂了)
self.myUrl = url + '?see_lz=1'
self.datas = []
self.myTool = HTML_Tool()

def baidu_tieba(self):
# 读取页面的原始信息并将其从utf-8解码
myPage = urllib2.urlopen(self.myUrl).read().decode('utf-8')
# 计算只看楼主的话一共有多少页
endPage = self.page_counter(myPage)
# 获取该帖的标题
title = self.find_title(myPage)
#在print里,逗号,加号,%占位符 都是一个作用(逗号多会输出一个空格)
print u'标题:',title
# 保存得到的数据到本地
self.save_data(self.myUrl,title,endPage)

#用来计算一共有多少页
def page_counter(self,myPage):
# 正则表达式匹配 "共有<span class="red">12</span>页" 来获取一共有多少页(在页面按F12观察),search函数是查找匹配的内容,没找到返回None
myMatch = re.search(r'class="red">(\d+?)</span>',myPage,re.S)
if myMatch:
#group()和group(0)相同,是返回整个被匹配的字符串(即列表的第一个元素是myPage),group(1)是返回匹配到的部分(即列表的第二个元素是(\d+?)匹配到的,也就是页数)
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'<h3.*?>(.*?)</h3>',myPage,re.S)
title = u'暂无标题'
if myMatch:
title = myMatch.group(1)
else:
print u'找不到标题'
# 文件名不能包含以下字符: \ / : * ? " < > |
<span style="white-space:pre"> </span>title=title.replace('\\','').replace('/','').replace(':','').replace('*','').replace('?','').replace('"','').replace('>','').replace('<','').replace('|','')
return title

#存储数据到文件中
def save_data(self,url,title,endPage):
#先获得数据
self.get_data(url,endPage)
#保存到本地。open函数打开文件,我用的绝对路径,\\表示转义(等于\),W+是读写模式,文件名是title.txt
f = open('E:\\pytest\\pyget\\test23_tieba\\' + title + '.txt','w+')
#写文件,self.datas在初始化类时就有定义
f.writelines(self.datas)
#关文件
f.close()
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()
#将myPage中的内容处理一下
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')

#程序入口处
bdurl = str(raw_input(u'请输入帖子网址(不是只看楼主的):\n'))
#例如http://tieba.baidu.com/p/2913803667?see_lz=1&pn=8
#上边地址的问号加上后边的see啥啥啥就是点击只看楼主之后的网址,输入时输入问号之前的就行
mySpider = Baidu_Spider(bdurl)
mySpider.baidu_tieba()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 爬虫 博客 百度