同样是参考网上教程,编写爬取贴吧帖子的内容,同时把爬取的帖子保存到本地文档:

#!/usr/bin/python
#_*_coding:utf-8_*_
import urllib
import urllib2
import re
import sys

reload(sys)
sys.setdefaultencoding("utf-8")
#处理页面标签,去除图片、超链接、换行符等
class Tool:
#去除img标签,7位长空格
removeImg = re.compile('<img.*?>| {7}|')
#删除超链接标签
removeAddr = re.compile('<a.*?>|</a>')
#把换行的标签替换为\n
replaceLine = re.compile('<tr>|<div>|</div>|</p>')
#把表格制表<td>替换为\t
replaceTD = re.compile('<td>')
#把段落开头换为\n加两个空格
replacePara = re.compile('<p.*?>')
#把换行符或双换行符替换为\n
replaceBR = re.compile('<br><br>|<br>')
#将其余标签剔除
removeET = re.compile('<.*?>')

#去除匹配到Tool
def replace(self,x):
x = re.sub(self.removeImg,"",x)
x = re.sub(self.removeAddr,"",x)
#x = re.sub(self.replaceLine,"\n",x)
#x = re.sub(self.replaceTD,"\t",x)
#x = re.sub(self.replacePara,"\n ",x)
#x = re.sub(self.replaceBR,"\n",x)
x = re.sub(self.removeET,"",x)
#strip()将前后多余内容删除
return x.strip().encode('utf-8')
#百度贴吧爬虫练习
class BDTB:

#初始化,传入地址,是否只看楼主的参数
def __init__(self,baseUrl,seeLz,floorTag):
#base链接地址
self.baseURL = baseUrl
#是否只看楼主
self.seeLZ = '?seelz=' + str(seeLz)
#HTML剔除标签工具Tool
self.tool = Tool()
#全局file变量,文件写入操作对象
self.file = None
#楼层标识,初始化为1
self.floor = 1
#默认的标题,如果没有成功获取到标题的话则会用这个标题
self.defaultTitle = u"百度贴吧"
#是否写入楼分隔符的标记
self.floorTag = floorTag

#传入页码,获取该页帖子的代码
def getPage(self,pageNum):
try:
url = self.baseURL + self.seeLZ + '&pn=' + str(pageNum)
request = urllib2.Request(url)
response = urllib2.urlopen(request)
tbPage = response.read().decode('utf-8')
#print tbPage
return tbPage
#链接报错的原因
except urllib2.URLError, e:
if hasattr(e,"reason"):
print u'链接百度贴吧失败,错误原因:',e.reason
return None

#获取帖子标题
def getTitle(self,page):
page = self.getPage(1)
#正则匹配贴吧标题
pattern = re.compile('<h3 class="core_title_txt.*?>(.*?)</h3>',re.S)
result = re.search(pattern,page)
if result:
#输出标题
#print result.group(1)
return result.group(1).strip()
else:
return None

#获取帖子一共有多少页
def getPageNum(self,page):
page = self.getPage(1)
#正则匹配帖子总共有多少页
pattern = re.compile('<li class="l_reply_num.*?</span>.*?<span.*?>(.*?)</span>',re.S)
result = re.search(pattern,page)
if result:
#输出页码数
#print result.group(1)
return result.group(1).strip()
else:
print None

#获取帖子每一个楼层的内容
def getContent(self,page):
#正则匹配每一个楼层的内容
pattern = re.compile('<div id="post_content.*?>(.*?)</div>',re.S)
items = re.findall(pattern,page)
#floor = 1
contents = []
for item in items:
#将文本进行去除标签处理,同时在前后加入换行符
content = "\n" + self.tool.replace(item) + "\n"
contents.append(content.encode('utf-8'))
#print floor,u"楼-----------------------"
#print content
#floor += 1
return contents

#设置文件的标题
def setFileTitle(self,title):
#如果标题不是None,即成功获取到标题
if title is not None:
self.file = open(title + ".txt","w+")
else:
self.file = open(self.defaultTitle + ".txt","w+")

#向文件写入每一楼层的信息
def writeData(self,contents):
#遍历楼层
for item in contents:
if self.floorTag == '1':
#楼之间使用的分隔符
floorLine = "\n--------------" + str(self.floor) + "楼-----------------\n"
self.file.write(unicode(floorLine,"utf-8"))
self.file.write(unicode(item,"utf-8"))
self.floor += 1

def start(self):
indexPage = self.getPage(1)
pageNum = self.getPageNum(indexPage)
title = self.getTitle(indexPage)
self.setFileTitle(title)
if pageNum == None:
print "URL已失效,请重试"
return
try:
print "该帖子共有" + str(pageNum) + "页"
for i in range(1,int(pageNum) + 1):
print "正在写入第" + str(i) + "页数据"
page = self.getPage(i)
contents = self.getContent(page)
self.writeData(contents)
except IOError,e:
print "写入异常,原因" + e.message
finally:
print "写入任务完成"
print u"请输入帖子代号"
baseURL = 'http://tieba.baidu.com/p/' + str(raw_input(u'http://tieba.baidu.com/p/'))
seeLZ = raw_input("是否只获取楼主发言,是输入1,否输入0\n")
floorTag = raw_input("是否写入楼层信息,是输入1,否输入0\n")
bdtb = BDTB(baseURL,seeLZ,floorTag)
bdtb.start()

Python爬虫爬取百度贴吧的帖子的更多相关文章

  1. Python爬虫 - 爬取百度html代码前200行

    Python爬虫 - 爬取百度html代码前200行 - 改进版,  增加了对字符串的.strip()处理 源代码如下: # 改进版, 增加了 .strip()方法的使用 # coding=utf-8 ...

  2. python爬虫-爬取百度图片

    python爬虫-爬取百度图片(转) #!/usr/bin/python# coding=utf-8# 作者 :Y0010026# 创建时间 :2018/12/16 16:16# 文件 :spider ...

  3. 写一个python 爬虫爬取百度电影并存入mysql中

    目标是利用python爬取百度搜索的电影 在类型 地区 年代各个标签下 电影的名字 评分 和图片连接 以及 电影连接 首先我们先在mysql中建表 create table liubo4( id in ...

  4. python爬虫—爬取百度百科数据

    爬虫框架:开发平台 centos6.7 根据慕课网爬虫教程编写代码 片区百度百科url,标题,内容 分为4个模块:html_downloader.py 下载器 html_outputer.py 爬取数 ...

  5. Python爬虫爬取百度贴吧的图片

    根据输入的贴吧地址,爬取想要该贴吧的图片,保存到本地文件夹,仅供参考: #!/usr/bin/python#_*_coding:utf-8_*_import urllibimport urllib2i ...

  6. Python爬虫爬取百度翻译之数据提取方法json

    工具:Python 3.6.5.PyCharm开发工具.Windows 10 操作系统 说明:本例为实现输入中文翻译为英文的小程序,适合Python爬虫的初学者一起学习,感兴趣的可以做英文翻译为中文的 ...

  7. Python爬虫-爬取百度贴吧帖子

    这次主要学习了替换各种标签,规范格式的方法.依然参考博主崔庆才的博客. 1.获取url 某一帖子:https://tieba.baidu.com/p/3138733512?see_lz=1&p ...

  8. python --爬虫--爬取百度翻译

    import requestsimport json class baidufanyi: def __init__(self, trans_str): self.lang_detect_url = ' ...

  9. 利用python的爬虫技术爬取百度贴吧的帖子

    在爬取糗事百科的段子后,我又在知乎上找了一个爬取百度贴吧帖子的实例,为了巩固提升已掌握的爬虫知识,于是我打算自己也做一个. 实现目标:1,爬取楼主所发的帖子 2,显示所爬去的楼层以及帖子题目 3,将爬 ...

随机推荐

  1. TodoMVC中的Backbone+MarionetteJS+RequireJS例子源码分析之三 Views

    这个版本的TodoMVC中的视图组织划分比较细,更加易于理解,这也得益于Marionette为我们带来了丰富的视图选择,原生的backbone只有views,而Marionette则有itemview ...

  2. 2012 Multi-University #10

    容斥原理 A Number Sequence 题意:给出n个数,b1,b2,b3……bn,构造n个数,a1,a2,……an(ai>1),使得a1*a2*a3……an=b1*b2……bn 分析:容 ...

  3. Pig基础学习【持续更新中】

    *本文参考了Pig官方文档以及已有的一些博客,并加上了自己的一些知识性的理解.目前正在持续更新中.* Pig作为一种处理大规模数据的高级查询语言,底层是转换成MapReduce实现的,可以作为MapR ...

  4. Ajax缓存解决办法(转载)

    项目有时要用一些Ajax的效果,因为比较简单,也就没有去用什么Ajax.NET之类的东西,手写代码也就实现了.. 第二天,有人向我报告错误:说是只有第一次读取的值正常,后面的值都不正常:我调试了一下 ...

  5. Spring注入方式及注解配置

    一:基于xml的DI(Dependency Injection) 注入类型: 定义学生Student实体类和小汽车Car实体类:进行封装和生成ToString(),并自定义属性Car Student ...

  6. *HDU1150 二分图

    Machine Schedule Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) ...

  7. C#的7个原则

    C#的七个原则如下: 1.单一职责原则(Single Responsibility Principle, SRP):一个类只负责一个功能领域中的相应职责. 2.开闭原则(Open-Closed Pri ...

  8. DBUtils

    DBUtils中核心对象 > QueryRunner类 它提供了操作数据增删改查的方法 query() 执行select语句的 update() 执行insert update delete 语 ...

  9. php获得http头部信息的方法

    $url = 'http://www.baidu.com'; $fp = fopen($url, 'r'); $meta_data = stream_get_meta_data($fp); var_d ...

  10. Get请求中文乱码的几种解决方式

    1.将字符串转码:new String("xxxxx".getBytes("iso-8859-1"),"utf-8")         这种 ...