python爬取百度贴吧

本文介绍如何使用Python进行网络爬虫,抓取百度贴吧的数据。参考链接提供了一个详细的教程,涵盖了爬虫的基本步骤和技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import urllib2  
import re

#----------- 处理页面上的各种标签 -----------  
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):  
        x = self.BgnCharToNoneRex.sub("",x)  
        #re.compile()的sub方法,sub(repl, string[, count]),使用repl替换string中每一个匹配的子串后返回替换后的字符串
        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])    #str的方法,用t[1]替换t[0]
        return x    

class Baidu_Spider:  
    # 申明相关的属性  
    def __init__(self,url):    
        self.myUrl = url + '?see_lz=1'  
        self.datas = []  
        self.myTool = HTML_Tool()  #调用HTML_Tool实例
        print u'已经启动百度贴吧爬虫,咔嚓咔嚓'  

     # 初始化加载页面并将其转码储存  
    def baidu_tieba(self):  
        # 读取页面的原始信息并将其从utf-8转码  
        myPage = urllib2.urlopen(self.myUrl).read().decode("utf-8")  #myPage为读取的网页源码
        # 计算楼主发布内容一共有多少页  
        endPage = self.page_counter(myPage)   #调用自定义page_count函数,返回结果3
        # 获取该帖的标题  
        title = self.find_title(myPage)       #调用自定义find_title函数,返回结果【我是歌手】盘点那些曾经叱咤风雨的华语乐坛顶级音乐人和歌
        print u'文章名称:' + title  
        # 获取最终的数据  
        self.save_data(self.myUrl,title,endPage)  #调用自定义的save_data函数

    #用来计算楼主的回复贴一共有多少页  
    def page_counter(self,myPage):  
        # 匹配 "共有<span class="red">3</span>页" 来获取一共有多少页  
        myMatch = re.search(r'<span class="red">(\d+?)</span>', myPage, re.S) #不匹配,返回为None
        #查找字符串中可以匹配成功的子串
        if myMatch:    
            endPage = int(myMatch.group(1))  
            print u'爬虫报告:发现楼主共有%d页的原创内容' % endPage  
        else:  
            endPage = 0  
            print u'爬虫报告:无法计算楼主发布内容有多少页!'  
        return endPage  

    # 用来寻找该帖的标题  
    def find_title(self,myPage):  
        # 匹配 <h1 class="core_title_txt" title="">xxxxxxxxxx</h1> 找出标题  
        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('>','').replace('<','').replace('|','')  
        return title  

    # 用来存储楼主发布的内容  
    def save_data(self,url,title,endPage):  
        # 加载页面数据到数组中  
        self.get_data(url,endPage)  
        # 打开本地文件  
        f = open('/Users/enniu/Downloads/' + title + '.txt','w+')  
        f.writelines(self.datas)  
        f.close()  
        print u'爬虫报告:文件已下载到本地并打包成txt文件'  
        #print u'请按任意键退出...'  
        #raw_input();  

    # 获取页面源码并将其存储到数组中  
    def get_data(self,url,endPage):  #将endPage=3传入
        url = url + '&pn='  
        for i in range(1,endPage+1):  
            print u'爬虫报告:爬虫%d号正在加载中...' % i  
            myPage = urllib2.urlopen(url + str(i)).read()  
            # 将myPage中的html代码处理并存储到datas里面  
            self.deal_data(myPage.decode('utf-8'))  #将每一页读取的源代码交给deal_data处理

    # 将内容从页面代码中抠出来  
    def deal_data(self,myPage):  
        myItems = re.findall('id="post_content.*?>(.*?)</div>',myPage,re.S)  #re.S也能匹配换行符
        for item in myItems:  
            data = self.myTool.Replace_Char(item.replace("\n","").encode('utf-8'))  
            self.datas.append(data+'\n')  

if __name__=='__main__':
    bdurl='http://tieba.baidu.com/p/4849798555'
    mySpider = Baidu_Spider(bdurl)  
    mySpider.baidu_tieba()  

结果如下:

已经启动百度贴吧爬虫,咔嚓咔嚓
爬虫报告:发现楼主共有3页的原创内容
文章名称:【我是歌手】盘点那些曾经叱咤风雨的华语乐坛顶级音乐人和歌手
爬虫报告:爬虫1号正在加载中...
爬虫报告:爬虫2号正在加载中...
爬虫报告:爬虫3号正在加载中...
爬虫报告:文件已下载到本地并打包成txt文件
[Finished in 3.8s]

参考链接:
http://blog.youkuaiyun.com/pleasecallmewhy/article/details/8934726

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值